简体   繁体   中英

Sort nested arrays alphabetically

How can I sort both arrays alphabetically?

I've tried to sort it but it only does the top level array and not the location array.

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

This is an example of some of the 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
                )

        )

Since you already use a foreach, we'll use this one to sort your location array :

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

 sort($output);

like that your both array will be sort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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