使用相同的键和值对数组进行分组,并使用它创建json数据

时间:2014-04-30 08:45:03

标签: php arrays json

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]
} ....

2 个答案:

答案 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)

我会分两步完成:

  1. 将同一宗教聚集在一起并收集计数
  2. 将结果映射到最终数据数组
  3. 所以:

    $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);
    

    请参阅:array_reduce() json_encode()