php 如何按特定子数组值对多维数组进行分组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2189626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:25:35  来源:igfitidea点击:

How to group a multidimensional array by a particular subarray value?

phparraysmultidimensional-arraygrouping

提问by n00b0101

I have a multidimensional array and am trying to group them according to the value in a specific column.

我有一个多维数组,正在尝试根据特定列中的值对它们进行分组。

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 forloop and say while $i < 7, because I won't know that 7is 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...

我正在尝试按 对它们进行分组level,但实际上我事先并不知道级别。所以,我不能把它放在一个for循环中然后说while $i < 7,因为我不知道这7是 level 键的最大值,坦率地说,我不确定我是否需要这样做,即使我做过...

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
          )
)

What I'm hoping to produce:

我希望生产什么:

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
                 )
          )
)

采纳答案by Gerard Banasig

You need to group them by levelfirst

你需要将它们按级别第一

Use foreachto loop into array check if the level is the same with the previous item then group it with that array

使用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);


The output of print($grouparr);will display like the format you hoped for

print($grouparr)的输出将显示为您希望的格式

You can also try to

你也可以尝试

print($grouparr[7]);

Will display

会显示

 [7] => Array (
      [4] => Array (
             [cust] => XT7434
             [type] => standard
             )
      )

Or

或者

print($grouparr[3]);

Will display

会显示

[3] => Array (
      [2] => Array (
             [cust] => XT8922
             [type] => premier
             )

      [3] => Array (
             [cust] => XT8816
             [type] => permier
             )
      )

回答by Mike

Best way, if you have control over building the initial array, is just set things up like that at the start as you add entries.

最好的方法是,如果您可以控制构建初始数组,只需在添加条目时在开始时进行设置。

If not then build a temporary array to sort:

如果没有,则构建一个临时数组进行排序:

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

Leaves you with the form you wanted and everything referenced together.

留下你想要的表格和所有引用的东西。

Build the array like that in the first place though if at all possible.

如果可能的话,首先构建这样的数组。

回答by Kevin Hagerty

Here is the solution I landed on for an identical problem, wrapped as a function:

这是我针对相同问题找到的解决方案,包装为函数:

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

To sort $myarray by the key named "level" just do this:

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

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

Or if you didn't want it as a function, just for a one time use, this would create $myNewArray from $myArray grouped by the key 'level'

或者,如果您不希望它作为一个函数,只使用一次,这将从按“级别”键分组的 $myArray 创建 $myNewArray

foreach ($myArray as $key=>$val) $myNewArray[$val['level']][]=$val;

回答by Farzher

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');

回答by user4155960

  $result = array();
    foreach ($yourArrayList as $data) {
        $id = $data['level'];
        if (isset($result[$id])) {
            $result[$id][] = $data;
        } else {
            $result[$id] = array($data);
        }
    }

回答by VIPAN KUMAR

Best ans.

最好的答案。

    $levels = array_unique(array_column($records, 'level'));

    $data = array();

    foreach($records as $key => $value){ 

    $data[$levels[array_search($value['level'],$levels )]][] = $value ; 

    }

    print_r($data); 

回答by user6394097

function _group_by($array,$key,$keyName)
    {
          $return = array();

          foreach($array as $val) {
              $return[$keyName.$val[$key]][] = $val;
          }
         return $return;

    }  //end of function