首页 > 解决方案 > 重构 PHP 数组以根据数组元素对记录进行分组

问题描述

我有一个如下所述的 PHP 数组

$prejon=Array ( 
[0] => Array ( [ldate] => 2020-01-02 [eid] => 801 [nm] => Shivaraj ) 
[1] => Array ( [ldate] => 2020-01-02 [eid] => 130 [nm] => Praveen Kumar ) 
[2] => Array ( [ldate] => 2020-01-03 [eid] => 690 [nm] => Anand ) 
[3] => Array ( [ldate] => 2020-01-04 [eid] => 2300 [nm] => Bhogendranadh ) 
[4] => Array ( [ldate] => 2020-01-04 [eid] => 2168 [nm] => Sravan ) 
[5] => Array ( [ldate] => 2020-01-05 [eid] => 2312 [nm] => Deepti ) 
[6] => Array ( [ldate] => 2020-01-05 [eid] => 2161 [nm] => Sourabh )
);

我想通过根据字段 ldate 和需要数组对记录进行分组来重组数组,如下所述

$OutputArray=(
[2020-01-02]=>Array([0]=>Array([eid] => 801 [nm] => Shivaraj) [1]=>Array([eid] => 130 [nm] => Praveen Kumar )
[2020-01-03]=>Array([0]=>Array([eid] => 690 [nm] => Anand))
[2020-01-04]=>Array([0]=>Array([eid] => 2300 [nm] => Bhogendranadh) [1]=>Array([eid] => 2168 [nm] => Sravan )
[2020-01-05]=>Array([0]=>Array([eid] => 2312 [nm] => Deepti) [1]=>Array([eid] => 2161 [nm] => Sourabh )
); 
I wrote below peace of code to do it but its not working 

$l2=array();
$x=0;
for($x=0;x<count($preJon);$x++)
{
    if($l2.array_key_exists($preJon[$x]['ldate'],$l2))
    {
        $l2[$preJon[$x]['ldate']] []=array('eid'=>$preJon[$x]['eid'],'nm'=>$preJon[$x]['nm']);
    }
    else
    {
        $l2[]=array($preJon[$x]['ldate']=>array('eid'=>$preJon[$x]['eid'],'nm'=>$preJon[$x]['nm']));
    }
}

I am unable to figure out the logic, if you can help it would be great

thanks in advance 

标签: phparrays

解决方案


您的逻辑似乎还可以,这更像是语法问题:

$result = array();
foreach($prejon as $item)
{
    $key = $item['ldate'] ; // new key of the element

    $new_item = $item ; // copy of the item
    unset($new_item['ldate']); // remove ldate from the item to insert

    // if the key doesn't already exist in the result array, create it
    if( !array_key_exists($key, $result) )
        $result[$key] = array() ; // initialize with empty array
    $result[$key][] = $new_item ; // append the new item to the key array
}

print_r($result);

推荐阅读