简体   繁体   English

在PHP中排序多维数组

[英]sorting a multi dimensional array in php

I have an array of arrays, as such 我有一个数组的数组

$statuses = array(
  [0] => array('id'=>10, 'status' => 'active'),
  [1] => array('id'=>11, 'status' => 'closed'),
  [2] => array('id'=>12, 'status' => 'active'),
  [3] => array('id'=>13, 'status' => 'stopped'),
)

I want to be able to make a new array of arrays and each of those sub arrays would contain the elements based on if they had the same status. 我希望能够创建一个新的数组数组,并且这些子数组中的每个子数组都将包含基于其状态相同的元素。 The trick here is, I do not want to do a case check based on hard coded status names as they can be random. 这里的窍门是,我不想基于硬编码状态名称进行案例检查,因为它们可以是随机的。 I want to basically do a dynamic comparison, and say "if you are unique, then create a new array and stick yourself in there, if an array already exists with the same status than stick me in there instead". 我基本上想进行动态比较,然后说:“如果您是唯一的,那么创建一个新数组并将您自己粘在其中,如果已经存在一个状态相同的数组而不是将我粘在其中”。 A sample result could look something like this. 样本结果可能看起来像这样。

Ive really had a challenge with this because the only way I can think to do it is check every single element against every other single element, and if unique than create a new array. 我确实对此提出了挑战,因为我认为要做到这一点的唯一方法是将每个单个元素与其他每个单个元素进行检查,并且如果唯一,则要创建一个新数组。 This gets out of control fast if the original array is larger than 100. There must be some built in functions that can make this efficient. 如果原始数组大于100,则会很快失去控制。必须有一些内置函数可以使此方法高效。

<?php
$sortedArray = array(
    ['active'] => array(
        array(
            'id' => 10,
            'status' => 'active'
        ),
        array(
            'id' => 12,
            'status' => 'active'
        )
    ),
    ['closed'] => array(
        array(
            'id' => 11,
            'status' => 'active'
        )
    ),
    ['stopped'] => array(
        array(
            'id' => 13,
            'status' => 'active'
        )
    ),
)
$SortedArray = array();
$SortedArray['active'] = array();
$SortedArray['closed'] = array();
$SortedArray['stopped'] = array();

foreach($statuses as $Curr) {
    if ($Curr['status'] == 'active') { $SortedArray['active'][] = $Curr; }
    if ($Curr['status'] == 'closed') { $SortedArray['closed'][] = $Curr;  }
    if ($Curr['status'] == 'stopped') { $SortedArray['stopped'][] = $Curr;  }
}

You can also do it with functional way though it's pretty the same like Marc said. 您也可以使用功能方式来做到这一点,尽管它和Marc所说的一样。

$sorted = array_reduce($statuses, function($carry, $status) {
    $carry[$status['status']][] = $status;
    return $carry;
}, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM