我有一个多维数组,我试图根据重复值对数组进行分组。因此,我尝试按键对它们进行分组,但我无法根据键值对数组进行分组。B...
我有一个多维数组,我正在尝试根据重复值对该数组进行分组。
因此,我尝试按键对它们进行分组,但我无法根据键值对数组进行分组。
以下是原始数组
[
{
"league_id": 2,
"league_name": "BBBB",
"league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1722361078.png",
"order_number": 1,
"member_username": "A"
},
{
"league_id": 2,
"league_name": "BBBB",
"league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1722361078.png",
"order_number": 2,
"member_username": "B"
},
{
"league_id": 1,
"league_name": "AAAA",
"league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1724177635.png",
"order_number": 1,
"member_username": "C"
},
{
"league_id": 1,
"league_name": "AAAA",
"league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1724177635.png",
"order_number": 2,
"member_username": "D"
},
]
我想将该数组重新排列为下面的输出数组:
[
{
"league_id": 2,
"league_name": "BBBB",
"league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1722361078.png",
"users": [{
"order_number": 1,
"member_username": "A"
}, {
"order_number": 2,
"member_username": "B"
}]
},
{
"league_id": 1,
"league_name": "AAAA",
"league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1722361078.png",
"users": [{
"order_number": 1,
"member_username": "C"
}, {
"order_number": 2,
"member_username": "D"
}]
}
]
有什么想法吗?如何做到这一点。
谢谢
感谢@Olivier 指出了这个错误,这个错误会导致 $final_array
除当前迭代之外的所有用户都被添加。
我认为 foreach
循环可以帮你解决这个问题。
示例实现:
$array = []; // Your original array here
$final_array = []; // Initializing an empty array to store final result
foreach ($array as $item) {
// Check if item's league id is already present in $final_array or not
if (isset($final_array[$item['league_id']])) {
// If yes, then add to users
$final_array[$item['league_id']]['users'][] = [
"order_number" => $item['order_number'],
"member_username" => $item['member_username']
];
} else {
// If no, then add as a new element
$final_array[$item['league_id']] = [
"league_id" => $item['league_id'],
"league_name" => $item['league_name'],
"league_image" => $item['league_image'],
"users" => [
"order_number" => $item['order_number'],
"member_username" => $item['member_username']
]
];
}
}
// Uncomment the following line if you want to sort the $final_array according to league ids.
// $final_array = ksort($final_array);
// Since you need a non-associative array
$final_array = array_values($final_array);
echo $final_array; // The $final_array contains your desired array
因此, $final_array
是所需的数组。
我知道这 不是 最优 或 最有效的 方案 ,但如果您的数组不是很大,则上述实现就足够了。