-3
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] => 
    )

)

i need to group the array by the same key and value and create a json data with the grouped array.

For Eg: i need to display it as

{
name : 'Christian',
data :[4,2,4]
},
{name:'Hindu',
data:[3,2,1]
} ....
ReNiSh AR
  • 2,782
  • 2
  • 30
  • 42
krish
  • 221
  • 1
  • 4
  • 20

2 Answers2

1

Give this a go!

  • Create your own array
  • Loop through your current array ($arrArray)
  • Group elements, by adding them to $arrGrouped

The code

$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>';
ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
1

I would do this in two steps:

  1. Group the same religion together and gather the counts
  2. Map the result into the final data array

So:

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

See: array_reduce() json_encode()

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309