简体   繁体   中英

foreach loop nested array json php

How do I loop through the array to get the "converted_amount" values?

stdClass Object
(
[rows] => Array
    (
        [0] => stdClass Object
            (
                [components] => Array
                    (
                        [0] => stdClass Object
                           (
                                [amount] => 5033298.132349431
                                [count] => 1337
                                [rate] => 3.1398800
                                [converted_amount] => 1603021.9952863243
                            )

                        [1] => stdClass Object
                            (
                                [amount] => 458673.0026585825
                                [count] => 325
                                [rate] => 0.45260800
                                [converted_amount] => 1013400.4157520011
                            )

I have tried a foreach like this but it doesn't work. I think there should be something in-between components and converted_amount - maybe another foreach? I'm not sure.

foreach ($getexvolume as $vol) {
echo $vol['rows'][0]['components']['converted_amount'];}

You have an object instead if array. You must work with data as an object...

foreach ($getexvolume->rows as $row) {
    foreach ($row->components as $component) {
       echo $component->converted_amount;
    }
}
   echo $vol->rows[0]->components[0]->converted_amount;

You are mixing array and object. Your output is an object so you have to access it like one otherwise if you want to treat it like an array you have to convert it to an array. As for now you can use the above code.

A better solution which i think fits your problem is that you loop around your nested array like:

foreach($vol->rows[0]->components as $data){
echo $data->converted_amount;
}

Try this:

foreach ($getexvolume->rows[0]->components as $vol) {
       echo $vol->converted_amount;
}

The object you have is a mix of Arrays and Objects. Arrays can be addressed as $array['value'] but Objects must be addressed as $object->value .

echo $vol->rows[0]->components[0]->converted_amount;

However since you have multiple components, you will need a nested loop:

foreach ($getexvolume as $vol)
{
  foreach($vol->rows as $row)
  {
    foreach($row->component as $component)
    {
      echo $component->converted_amount;
    }
  }
}

(pseudocode - not tested).

Ideally the variable would be normalised as a multidimensional array or nested object first so you don't have to worry about syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM