Reputation: 67
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'];}
Upvotes: 0
Views: 1235
Reputation: 6456
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;
}
}
Upvotes: 1
Reputation: 344
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.
Upvotes: 0
Reputation: 347
Try this:
foreach ($getexvolume->rows[0]->components as $vol) {
echo $vol->converted_amount;
}
Upvotes: 0
Reputation: 8358
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;
}
Upvotes: 0