php - 重构 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
解决方案
您的逻辑似乎还可以,这更像是语法问题:
$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);
推荐阅读
- android - kotlin 编写 nfc 标签未能写入超过 4 页或任何数字
- reactjs - 将 redux 调度传递给函数的最佳方法是什么?
- r - Minimal Bookdown 书无法正确渲染。我该如何解决这个问题?
- node.js - 使用带有firebase功能的角度httpClient的CORS错误
- rust - 如何在 Yew 应用程序中包含睡眠功能?
- typescript - TS2531 对象可能为“空”,尽管在 for 循环中检查
- typescript - “无法对任意非 POJO 进行字符串化”和“无效的道具:道具的类型检查失败”警告
- python - For and If together - 数据框 Python
- python - 简单文件上传插件在提交时不返回文件 - django
- c - 如何使用 qsort 对结构数组进行排序