我尝试将数组格式化为highcharts支持的JSON对象。我在数据库中的数组如下:
Array
(
[0] => Array
(
[Group_ID] => 1
[Name] => A line graph
[month] => 4
[amount] => 7700
)
[1] => Array
(
[Group_ID] => 2
[Name] => B Line graph
[month] => 4
[amount] => 390
)
[2] => Array
(
[Group_ID] => 1
[Name] => A line graph
[month] => 5
[amount] => 5000
)
[3] => Array
(
[Group_ID] => 2
[Name] => B line graph
[month] => 5
[amount] => 210
)
)
我需要创建一个这样的数组,以便能够创建一个与高清兼容的JSON对象:
Array
(
[0] => Array
(
[name] => A revenue
[data] => Array
(
[4] => 7700 //amount for the fourth month
[5] => 5000 //amount for the fifth month
)
)
[1] => Array
(
[name] => B revenue
[data] => Array
(
[4] => 390 //amount for the fourth month
[5] => 210 //amount for the fifth month
)
)
)
我已经设法使用我的foreach来提出这个数组,但我似乎找不到正确的方法:
Array
(
[0] => Array
(
[name] => A line graph
[amount] => 7700
[month] => 4
)
[1] => Array
(
[name] => B line graph
[amount] => 390
[month] => 4
)
[2] => Array
(
[name] => A line graph
[amount] => 5000
[month] => 5
)
[3] => Array
(
[name] => B line graph
[amount] => 210
[month] => 5
)
)
我的预告:
foreach ($data as $key => $value) {
$r[] = [
'name' => $value['Line_GraphName'],
'data' => $value['amount'],
'month' => $value['month']
];
}
答案 0 :(得分:3)
您可以像这样简单地创建它:
foreach ($data as $value) {
$r[$value['Group_ID']]['name'] = $value['Line_GraphName'];
$r[$value['Group_ID']]['data'][$value['month']] = $value['amount'];
}
Group_ID
为键创建结果,并添加name
键和值data
数组并附加month
作为键,amount
作为值如果您不希望将Group_ID
作为密钥并想要重新编制索引:
$r = array_values($r);
答案 1 :(得分:0)
使用array_walk
和array_values
函数的解决方案:
$result = [];
array_walk($data, function($v) use(&$result) {
$key = $v['Group_ID'] . $v['Name'][0]; // compound key: "group_id + revenue's prefix"
if (!isset($result[$key])) {
$result[$key] = ['name' => $key[1] . " Revenue", 'data' => [$v['month'] => $v['amount']]];
} else {
$result[$key]['data'][$v['month']] = $v['amount'];
}
});
print_r(array_values($result));
输出:
Array
(
[0] => Array
(
[name] => A Revenue
[data] => Array
(
[4] => 7700
[5] => 5000
)
)
[1] => Array
(
[name] => B Revenue
[data] => Array
(
[4] => 390
[5] => 210
)
)
)