按特定值分组multidimensional array?

希望我能正确解释

我有一个multidimensional array,并试图根据一个键的值来对它们进行分组。

所以,我试图把他们按等级分组,但事实上我并不知道这个等级。 所以,不是我可以把它放在一个for循环中,并说$ 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 ) ) 

最好的办法是,如果你可以控制构build初始数组,只需在添加条目时就开始设置。

如果没有,那么build立一个临时数组进行sorting:

 foreach ($input_arr as $key => &$entry) { $level_arr[$entry['level']][$key] = $entry; } 

留下你想要的forms和一切引用在一起。

尽可能地build立这样的arrays。

 function group_assoc($array, $key) { $return = array(); foreach($array as $v) { $return[$v[$key]][] = $v; } return $return; } //Group the requests by their account_id $account_requests = group_assoc($requests, 'account_id'); 

下面是我解决相同的问题,作为一个函数包装的解决scheme:

 function arraySort($input,$sortkey){ foreach ($input as $key=>$val) $output[$val[$sortkey]][]=$val; return $output; } 

要按名为“level”的键sorting$ myarray,只需执行以下操作:

 $myArray = arraySort($myArray,'level'); 

或者,如果你不想把它作为一个函数,只需要一次使用,就可以从$ myArray创build$ myNewArray,这个$ myArray是由关键字“level”

 foreach ($myArray as $key=>$val) $myNewArray[$val['level']][]=$val; 
  $result = array(); foreach ($yourArrayList as $data) { $id = $data['level']; if (isset($result[$id])) { $result[$id][] = $data; } else { $result[$id] = array($data); } } 
 function _group_by($array,$key,$keyName) { $return = array(); foreach($array as $val) { $return[$keyName.$val[$key]][] = $val; } return $return; } //end of function