我有一个多维数组,正在尝试根据特定列中的值将它们分组。
我正在尝试按分组level,但实际上我不会事先知道该等级。因此,并不是像我可以将其放在for循环中然后说那样while $i < 7,因为我不知道这7是级别键的最大值,并且坦率地说,即使我我不确定这也不是我需要这样做的方式。做了…
level
for
while $i < 7
7
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 ) ) )
你需要将它们按 级别 第一
使用 foreach 循环进入数组,检查级别是否与上一个项目相同,然后将其与该数组分组
$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); 将显示为您希望的格式
您也可以尝试
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 ) )