Array
(
[0] => Array
(
[religion] => Christian
[emp_count] => 4
[b_name] => tripura
[branch_id] => 7
)
[1] => Array
(
[religion] => Christian
[emp_count] => 2
[b_name] => Tirunelveli
[branch_id] => 10
)
[2] => Array
(
[religion] => Christian
[emp_count] => 4
[b_name] => Madurai
[branch_id] => 12
)
[3] => Array
(
[religion] => Hindu
[emp_count] => 3
[b_name] => tripura
[branch_id] => 7
)
[4] => Array
(
[religion] => Hindu
[emp_count] => 4
[b_name] => Tirunelveli
[branch_id] => 10
)
[5] => Array
(
[religion] =>
[emp_count] => 0
[b_name] =>
[branch_id] =>
)
[6] => Array
(
[religion] =>
[emp_count] => 0
[b_name] =>
[branch_id] =>
)
[7] => Array
(
[religion] => Muslim
[emp_count] => 1
[b_name] => Tirunelveli
[branch_id] => 10
)
[8] => Array
(
[religion] =>
[emp_count] => 0
[b_name] =>
[branch_id] =>
)
)
我需要使用相同的键和值对数组进行分组,并使用分组数组创建json数据。
对于Eg:我需要将其显示为
{
name : 'Christian',
data :[4,2,4]
},
{name:'Hindu',
data:[3,2,1]
} ....
答案 0 :(得分:1)
放手一搏!
$arrArray
)$arrGrouped
$arrGrouped = array();
foreach($arrArray as $arrElement) {
if( array_key_exists($arrElement['religion'], $arrGrouped) ) {
$arrGrouped[$arrElement['religion']] += $arrElement['emp_count'];
} else {
$arrGrouped[$arrElement['religion']] = $arrElement['emp_count'];
}
}
echo '<pre>'. json_encode($arrGrouped, true) .'</pre>';
答案 1 :(得分:1)
我会分两步完成:
所以:
$result = array_reduce($array, function(&$result, $current) {
$result[$current['religion']][] = $current['emp_count'];
return $result;
}, []);
$data = [];
foreach ($result as $religion => $emp_counts) {
$data[] = [
'name' => $religion,
'data' => $emp_counts,
];
}
echo json_encode($data);