我有一个foreach循环将数据插入到多维数组中。
foreach ($charts_list as $chart_list) {
$category = $chart_list->category;
if (isset($chart_options[$category])) {
$chart_options[$category][] = $chart_list;
} else {
$chart_options[$category] = array($chart_list);
}
}
我得到一个这样的数组:
array:2 [▼
"twitter" => array:3 [▼
0 => {#271 ▼
+"id": 1
+"option_id": "DJ8RhoB"
+"title": "Followers Growth"
+"description": "See your followers growth"
+"category": "twitter"
+"created_at": "2016-05-09 10:44:54"
+"updated_at": "2016-05-09 10:44:54"
}
1 => {#272 ▼
+"id": 2
+"option_id": "tqP3Bri"
+"title": "Friends growth"
+"description": "See your friends growth"
+"category": "twitter"
+"created_at": "2016-05-09 10:45:24"
+"updated_at": "2016-05-09 10:45:24"
}
2 => {#273 ▼
+"id": 3
+"option_id": "v74DudJ"
+"title": "Statuses count"
+"description": "See your content growth"
+"category": "twitter"
+"created_at": "2016-05-09 10:45:46"
+"updated_at": "2016-05-09 10:45:46"
}
]
"facebook" => array:1 [▼
0 => {#274 ▼
+"id": 4
+"option_id": "fXj8wU5"
+"title": "Friends growth"
+"description": "See your friends growth"
+"category": "facebook"
+"created_at": "2016-05-09 13:08:21"
+"updated_at": "2016-05-09 13:08:21"
}
]
]
在顶级数组中,我需要将其设置为'category' => $category
,它应该打印"category": twitter
。我已尝试将$chart_options[$category]
设置为$chart_options['category' => $category. But I get a parse error
解析错误:语法错误,意外' =>' (T_DOUBLE_ARROW),期待']'`。如何将顶级数组设置为类别?
答案 0 :(得分:1)
看起来你实际上只是试图访问数组中的键以及值。
PHP foreach允许您通过指定其他参数来访问数组的键,而不是典型的:
foreach ($array as $value)
你可以这样做:
foreach ($array as $key => $value)
我希望这会有所帮助。
答案 1 :(得分:0)
它不是很清楚,但我想你想要这个:
$chart_options['category'] = $category;
答案 2 :(得分:0)
可能你需要尝试
$chart_options['category'][$category][] = $category;
答案 3 :(得分:0)
在else部分添加元素category
。
您的代码
$chart_options[$category] = array($chart_list);
更换后,它将如下所示
$chart_options['category'][$category] = array($chart_list);
^
完整代码
foreach ($charts_list as $chart_list) {
$category = $chart_list->category;
if (isset($chart_options[$category])) {
$chart_options[$category][] = $chart_list;
} else {
$chart_options['category'][$category] = array($chart_list);
}
}