简体   繁体   中英

How can I sort the keys of a multidimensional array?

array(1) {
  [0]=>
  array(1) {
    ["12345"]=>
    array(1) {
      ["orange"]=>
      string(46) "test.jpg"
      ["blue"]=>
      string(46) "test2.jpg"
      ["green"]=>
      string(46) "test3.jpg"
    }
  }
}

I want to sort it by key:

foreach ($array as $key => $value) {
      if(is_array($value)){
           foreach ($value as $k => $v) {
                usort($v);
                foreach ($v as $fileIterator => $fileData) {
                     echo $fileIterator;
                }
           }
      }
 }

This is the result

orange
blue
green

But I expect the order to be

blue
green
orange

Try this, You have to sort based on key so use ksort() . While using foreach() the duplicate of array is processed. In order to make changes in original array use '&' (calling by reference)

foreach ($array as $key => $value) {
      if(is_array($value)){
           foreach ($value as $k => &$v) {
                ksort($v);
                foreach ($v as $fileIterator => $fileData) {
                     echo $fileIterator;
                }
           }
      }
 }

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