如何按特定的子数组值对多维数组进行分组?
我有一个多维数组,正在尝试根据特定列中的值将它们分组.
I have a multidimensional array and am trying to group them according to the value in a specific column.
我正在尝试按level
对其进行分组,但实际上我不会事先知道该级别.因此,并不是像我可以将其放在for
循环中并说while $i < 7
一样,因为我不知道7
是级别键的最大值,并且坦率地说,我不确定这是怎么回事.即使我做了,我也需要这样做...
I'm trying to group them by level
, but I won't actually know the level beforehand. So, it's not like I can put it in a for
loop and say while $i < 7
, because I won't know that 7
is the maximum value for the level key, and frankly, I'm not sure that's how I would need to do it even if I did...
Array (
[0] => Array (
[cust] => XT8900
[type] => standard
[level] => 1
)
[1] => Array (
[cust] => XT8944
[type] => standard
[level] => 1
)
[2] => Array (
[cust] => XT8922
[type] => premier
[level] => 3
)
[3] => Array (
[cust] => XT8816
[type] => permier
[level] => 3
)
[4] => Array (
[cust] => XT7434
[type] => standard
[level] => 7
)
)
我希望产生什么:
Array (
[1] => Array (
[0] => Array (
[cust] => XT8900
[type] => standard
)
[1] => Array (
[cust] => XT8944
[type] => standard
)
)
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
)
您需要先按级别对其进行分组
You need to group them by level first
使用 foreach 进入数组,检查级别是否与上一个项目相同,然后将其与该数组分组
Use foreach to loop into array check if the level is the same with the previous item then group it with that array
$templevel=0;
$newkey=0;
$grouparr[$templevel]="";
foreach ($items as $key => $val) {
if ($templevel==$val['level']){
$grouparr[$templevel][$newkey]=$val;
} else {
$grouparr[$val['level']][$newkey]=$val;
}
$newkey++;
}
print($grouparr);
print($ grouparr); 的输出将显示为您希望的格式
The output of print($grouparr); will display like the format you hoped for
您也可以尝试
print($grouparr[7]);
会显示
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
或
print($grouparr[3]);
会显示
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)