【问题标题】:Sort and restructure multidimensional array in PHP?在 PHP 中排序和重组多维数组?
【发布时间】:2015-09-16 20:22:33
【问题描述】:

我有一个这样的数组:

$toSort = array(
    1 => 
        [
            'value' =>  8000,
            'key'   => 1007
        ],
    2 => 
        [
            'value' => 8001,
            'key'   => 1007
        ],
    3 => 
        [
            'value' => 8002,
            'key'   => 1013
        ],
);

我想像这样对它进行排序和重组:

$toSort = array(
    1007 => 
        [
            [0] =>  8000,
            [1] =>  8001
        ],
    1013 => 
        [
            [0] => 8002
        ]
);

它应该适用于随机数量的不同条目(不同的键/值)。

【问题讨论】:

  • 这不是排序。只需循环输入数组,并将值推送到具有相同键的输出数组的元素。
  • 排序是根据排序标准重新排列数组的元素,而不是重新组织数组的结构。

标签: php arrays sorting multidimensional-array


【解决方案1】:

这样的事情怎么样?

//A new array to move the data to.
var $result = array();

//Loop through the original array, and put all the data
//into result with the correct structure.
foreach($toSort as $e) {
    //If this key is not set yet, then create an empty array for it.
    if(!isset($result[$e['key']])) $result[$e['key']] = array()
    //Add the value to the end of the array.
    $result[$e['key']][] = $e['value'];
}

 //Sort the result, based on the key and not the value.
 //If you want it to be based on value, just use sort() instead.
 ksort($result)

 //If you want the sub-arrays sorted as well, loop through the array and sort them.
 foreach($result as $e)
     sort($e);

免责声明:我没有测试过这段代码。

【讨论】:

    【解决方案2】:
    $a=array(
        1 => 
            [
                'value' =>  8000,
                'key'   => 1007
            ],
        2 => 
            [
                'value' => 8001,
                'key'   => 1007
            ],
        3 => 
            [
                'value' => 8002,
                'key'   => 1013
            ],
    );
    
    $a=call_user_func(function($a){
        $ret=array();
    
        foreach($a as $v){
        if(array_key_exists($v['key'],$ret)){
            $ret[$v['key']][]=$v['value'];
            } else {
            $ret[$v['key']]=array($v['value']);
            }
            }
            return $ret;
    },$a);
    var_dump($a);
    

    【讨论】:

      【解决方案3】:

      在使用方括号语法将数据推入密钥之前,您无需检查密钥是否存在。

      功能风格:(Demo)

      var_export(
          array_reduce(
              $toSort,
              function($result, $row) {
                  $result[$row['key']][] = $row['value'];
                  return $result;
              },
              []
          )
      );
      

      基本循环加数组解构:(Demo)

      $result = [];
      foreach ($toSort as ['value' => $value, 'key' => $key]) {
          $result[$key][] = $value;
      }
      var_export($result);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-11
        相关资源
        最近更新 更多