Home > Enterprise >  how to retrieve data by index in php
how to retrieve data by index in php

Time:07-15

i have data in this

 "method": [
        {
          "id": "626",
          "rating": "936.6"
        },
        {
          "id": "631",
          "rating": "332"
        }
      ]

I made a loop, in this script.. and I want to retrieve rating data based on index because there is a special need, how?

<?php foreach($res['method'] as $key=>$row) { ?>    
   
    <?php echo [0]['rating']; ?> // rating index 0
    <?php echo [1]['rating']; ?> // rating index 1
    //I retrieve data by index this way but error Undefined index: rating

<?php } ?>

CodePudding user response:

When you want to access an array by an index, you have to write the array variable name first. Example: $res['method'][0] You also don't need that foreach loop if you just access the array by indexes, no more. You don't even need $key.

CodePudding user response:

In the following the indexes of the rows aren't referenced. You can just loop through a collection, and pick out the attributes you want.

<?php

$rows = 
[
    [
        'name' => 'Bob',
        'occupation' => 'Builder'
    ],
    [
        'name' => 'Pat',
        'occupation' => 'Postie'
    ]
];

foreach ($rows as $index => $row) {
    echo $row['name'], ' is a ', $row['occupation'], ".\n";
}

Output:

Bob is a Builder.
Pat is a Postie.
  •  Tags:  
  • php
  • Related