给出如下数组:
$z = [
"cat lovers" => [
"name" => "cat lovers",
"impressions" => 2038,
"ctr" => 0.032875368007851,
"actions" => [
[
"action_type" => "attention_event",
"value" => "232",
],
[
"action_type" => "landing_page_view",
"value" => "18",
],
],
"shorty kodi" => [
"name" => "shorty kodi",
"impressions" => 534,
"ctr" => 0.041198501872659,
"actions" => [
[
"action_type" => "attention_event",
"value" => "56",
],
[
"action_type" => "landing_page_view",
"value" => "7",
]
]
]
以下代码运行时没有错误:
foreach($z as $i) {
print_r(array_column($i["actions"], "action_type"));
}
但是如果我们将print_r函数删除为:
foreach($z as $i) {
$b = array_column($i["actions"], "action_type");
}
导致错误说:
PHP error: Undefined index: actions on line 2
知道为什么吗?
谢谢
答案 0 :(得分:1)
工作正常,我刚检查过。
将print_r($b);
放在foreach
内或之后。您将获得与第一个foreach
相同的结果。
答案 1 :(得分:0)
提供的数组有语法错误。
试试这个:
$z = [
"cat lovers" => [
"name" => "cat lovers",
"impressions" => 2038,
"ctr" => 0.032875368007851,
"actions" => [
[
"action_type" => "attention_event",
"value" => "232",
],
[
"action_type" => "landing_page_view",
"value" => "18",
],
]
],
"shorty kodi" => [
"name" => "shorty kodi",
"impressions" => 534,
"ctr" => 0.041198501872659,
"actions" => [
[
"action_type" => "attention_event",
"value" => "56",
],
[
"action_type" => "landing_page_view",
"value" => "7",
]
]
]
];
foreach($z as $i) {
$b = array_column($i["actions"], "action_type");
}
答案 2 :(得分:0)
我不知道出了什么问题,但我应对并粘贴了你的代码,而且工作正常。
这就是我所做的。
$z = [
"cat lovers" => [
"name" => "cat lovers",
"impressions" => 2038,
"ctr" => 0.032875368007851,
"actions" => [
[
"action_type" => "attention_event",
"value" => "232",
],
[
"action_type" => "landing_page_view",
"value" => "18",
],
],
"shorty kodi" => [
"name" => "shorty kodi",
"impressions" => 534,
"ctr" => 0.041198501872659,
"actions" => [
[
"action_type" => "attention_event",
"value" => "56",
],
[
"action_type" => "landing_page_view",
"value" => "7",
]
]
]
]];
$b = "";
foreach($z as $i) {
$b=array_column($i["actions"], "action_type");
}
print_r($b);
答案 3 :(得分:0)
对不起,我发现原因很简单。当我测试它时,阵列实际上很长,并且在其中一个元素中,没有"动作"索引,所有其余的都有!
这就是为什么当循环每个时,它会在那个上失败。
感谢您的所有反馈。