Thursday, 30 August 2018

Group the array with the same key and value and create json data with it

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


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>';

0 comments:

Post a Comment