按列值对数据行进行分组,并重组为关联多维数组
我正在尝试将数组的索引数组更改为新的数组结构。我的数据如下:
$arr = array(
array( "year" => 1921, "name" => "bob" ),
array( "year" => 1944, "name" => "steve" ),
array( "year" => 1944, "name" => "doug" ),
array( "year" => 1921, "name" => "jim" ),
);
我想重新创建一个新数组,将它们分组到同一年。我能想到的最好方法是将年份指定为关键字,这样任何包含该年的行都会添加到该关键字中,但这不是我要查找的输出。我需要的是它在下面列出的方式。
"data": [
{
"year":"1921",
"names": [
{ "name":"bob" }, { "name":"jim"}
]
},
{
"year":1944",
"names": [
{ "name":"steve" }, { "name":"doug "}
]
}
解决方案
您不需要预先提取唯一年份,也不需要在嵌套循环中使用条件。只需使用临时一级键将数据推送到结果集中,循环完成后再移除临时键。
这可确保年份唯一,但允许名称重复。
编码:(Demo)
$arr = [
["year" => 1921, "name" => "bob"],
["year" => 1944, "name" => "steve"],
["year" => 1944, "name" => "doug"],
["year" => 1921, "name" => "jim"],
];
foreach ($arr as $item) {
$result[$item['year']]['year'] = $item['year'];
$result[$item['year']]['names'][] = ['name' => $item['name']];
}
echo json_encode(
['data' => array_values($result)],
JSON_PRETTY_PRINT // for better visualization
);
输出:
{
"data": [
{
"year": 1921,
"names": [
{
"name": "bob"
},
{
"name": "jim"
}
]
},
{
"year": 1944,
"names": [
{
"name": "steve"
},
{
"name": "doug"
}
]
}
]
}
相关文章