Coold Coold - 4 months ago 41
JSON Question

Access the values in array php

I am trying to access the values of an array.

Array ( [0] => stdClass Object ( [action_type] => comment [value] => 19074.125 ) [1] => stdClass Object ( [action_type] => like [value] => 2179.9 ) [2] => stdClass Object ( [action_type] => link_click [value] => 16.633202528886 ) [3] => stdClass Object ( [action_type] => offsite_conversion.fb_pixel_add_to_cart [value] => 451.45857988166 ) [4] => stdClass Object ( [action_type] => offsite_conversion.fb_pixel_complete_registration [value] => 897.60588235294 ) [5] => stdClass Object ( [action_type] => offsite_conversion.fb_pixel_initiate_checkout [value] => 1230.5887096774 ) [6] => stdClass Object ( [action_type] => offsite_conversion.fb_pixel_lead [value] => 372.17804878049 ) [7] => stdClass Object ( [action_type] => offsite_conversion.fb_pixel_purchase [value] => 2384.265625 ) [8] => stdClass Object ( [action_type] => offsite_conversion.fb_pixel_view_content [value] => 63.316597510373 ) [9] => stdClass Object ( [action_type] => post [value] => 8477.3888888889 ) [10] => stdClass Object ( [action_type] => post_like [value] => 193.15569620253 ) [11] => stdClass Object ( [action_type] => unlike [value] => 76296.5 ) [12] => stdClass Object ( [action_type] => page_engagement [value] => 15.168290258449 ) [13] => stdClass Object ( [action_type] => post_engagement [value] => 15.274574574575 ) [14] => stdClass Object ( [action_type] => offsite_conversion [value] => 43.39960182025 ) )


I need to access the value of [action_type] => offsite_conversion.fb_pixel_purchase [value] => 2384.265625 , how to get the value of only offsite_conversion.fb_pixel_purchase ??

these values comes from the foreach loop.

$r = $i->cost_per_action_type;

foreach($r as $key => $value){
echo $key["action_type"];
}


the array you are seeing is the print_r($x).

Answer

You're trying to treat object as array which doesn't simply working. Use arrow operator -> instead to get object value.

foreach($r as $val){
    echo $val->action_type;
}

In case you're really wanted it to be an array, make sure to implement interfaces that gives ability to treat object as an array ArrayAccess, Countable, etc. You can also extends ArrayObject class, too.

And, according to your comment

foreach($r as $val){
    if ($val->action_type == 'offsite_conversion.fb_pixel_purchase') {
        echo $val->value;
    }
}
Comments