Nenad Maric Nenad Maric - 4 months ago 19
SQL Question

Group arrays by key value

I have a problem approaching an issue i have, i need to group

arrays
by
key
value


I have 3 foreach functions

foreach ($report_phonecall as $key=>$value) {
$phonecalls[$value['datum']] = $value['broj'];
};
foreach ($report_meeting as $key=>$value) {
$meetings[$value['datum']] = $value['broj'];
}
foreach ($report_notes as $key=>$value) {
$notes[$value['datum']] = $value['broj'];
}


That give me
array


$phonecall = Array ( [2016-07-13] => 2 [2016-07-14] => 1 [2016-07-19] =>1 )
$meetings = Array ( [2016-07-13] => 1 [2016-07-14] => 1 )
$notes = Array ( [2016-07-19] => 1 )


I need to merge them into 1
array
foreach date like this

Array(2016-07-13 => array([phonecalls]=>2, [meetings]=>1, [notes]=>0)) 2016-07-14 => array([phonecalls]=>1, [meetings]=> 1, [notes]=>0).... etc


I want to group/sort them by key value.

Going by

$group_reports[$value[key]] = $value['broj'][$phonecalls][$meetings][$notes]


Im not sure how to define it

Answer

Please use below code for merge array

$finalArr = array();
foreach($phonecall as $key=>$val){
    $finalArr[$key]['phonecalls'] = $val;
    $finalArr[$key]['meetings'] = 0;
    $finalArr[$key]['notes'] = 0;
}

foreach($meetings as $key=>$val){
    if(array_key_exists($key, $finalArr)){
        $finalArr[$key]['meetings'] = $val;
    } else {
        $finalArr[$key]['phonecalls'] = 0;
        $finalArr[$key]['meetings'] = $val;
        $finalArr[$key]['notes'] = 0;
    }
}

foreach($notes as $key=>$val){
    if(array_key_exists($key, $finalArr)){
        $finalArr[$key]['notes'] = $val;
    } else {
        $finalArr[$key]['phonecalls'] = 0;
        $finalArr[$key]['meetings'] = 0;
        $finalArr[$key]['notes'] = $val;
    }
}
Comments