按键值对数组进行分组

时间:2016-07-19 12:19:12

标签: php mysql arrays foreach

我遇到问题时遇到问题,我需要arrays key

value进行分组

我有3个foreach函数

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

给我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 )

我需要将它们合并到1 array foreach日期,如此

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

我想按键值对它们进行分组/排序。

继续

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

我不确定如何定义

2 个答案:

答案 0 :(得分:2)

这样怎么样?

$phonecall = ['2016-07-13' => 2, '2016-07-14' => 1, '2016-07-19' => 1];
$meetings = ['2016-07-13' => 1, '2016-07-14' => 1];
$notes = ['2016-07-19' => 1];

// Get *all* possible dates
$keys = array_unique(array_keys($phonecall+$meetings+$notes));

foreach($keys as $key) {
    $final[$key] = [
            'phonecalls' => isset($phonecall[$key]) ? $phonecall[$key] : 0,
            'meetings'   => isset($meetings[$key])  ? $meetings[$key]  : 0,
            'notes'      => isset($notes[$key])     ? $notes[$key]     : 0
    ];
}

答案 1 :(得分:1)

请使用以下代码进行合并数组

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