我正在尝试访问数组的值。
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 ) )
我需要访问[action_type] =>的值offsite_conversion.fb_pixel_purchase [value] => 2384.265625,如何获取offsite_conversion.fb_pixel_purchase的值?
这些值来自foreach循环。
$r = $i->cost_per_action_type;
foreach($r as $key => $value){
echo $key["action_type"];
}
您看到的数组是print_r($ x)。
答案 0 :(得分:2)
如果要将结果用作数组而不是对象,请使用:
//will return an associative array
$x = json_decode($j, true);
在你的代码中,$ x是一个对象,而不是数组,因此foreach是不正确的。你应该处理你的代码并给出一些原因,你编码一个数组只是为了解码它并尝试使用它就像一个数组而不是对象。
如果您正在使用数组并且摆脱了编码,则应将Object更改为数组。 您可以在示例中将@ Chay22所做的内容作为数组:
foreach($r as $val){
if ($val[action_type] == 'offsite_conversion.fb_pixel_purchase') {
echo $val[value];
}
}
答案 1 :(得分:1)
您正在尝试将对象视为不仅仅是工作的数组。使用箭头操作符->
来获取对象值。
foreach($r as $val){
echo $val->action_type;
}
如果您真的希望它是一个数组,请确保实现能够将对象视为数组ArrayAccess
,Countable
等的接口。您还可以扩展{{ 3}}课程。
并且,根据您的ArrayObject
foreach($r as $val){
if ($val->action_type == 'offsite_conversion.fb_pixel_purchase') {
echo $val->value;
}
}