按字母顺序排列嵌套数组

时间:2018-02-20 10:30:01

标签: php arrays

如何按字母顺序对两个数组进行排序?

我尝试对它进行排序,但它只执行顶级数组而不是位置数组。

  $tmp = array();

  foreach($clients as $arg) {
    $tmp[$arg['contract']][] = $arg['location'];
  }

  $output = array();

  foreach($tmp as $type => $labels) {
    $output[] = array(
        'contract' => $type,
        'location' => $labels
    );
  }

  //sort the top array alphabetically
  sort($output);

这是一些输出的例子:

Array
(
    [0] => Array
        (
            [contract] => Aldi
            [location] => Array
                (
                    [0] => Pembroke Dock
                    [1] => Haverfordwest
                    [2] => Cardigan
                    [3] => Carmarthen
                    [4] => Tewksbury
                    [5] => Taunton
                    [6] => Cardiff
                    [7] => Bridgend
                    [8] => Port Talbot
                    [9] => Cullompton
                    [10] => Honiton
                    [11] => Bridgewater
                )

        )

    [1] => Array
        (
            [contract] => Babel
            [location] => Array
                (
                    [0] => Cheltenham
                )

        )

1 个答案:

答案 0 :(得分:2)

由于您已经使用了foreach,我们将使用此方法对您的位置数组进行排序:

 foreach($tmp as $type => $labels) {
    sort($labels);
    $output[] = array(
        'contract' => $type,
        'location' => $labels
    );   
 }

 sort($output);

就像你的两个数组都将排序