Skip to content
Advertisement

PHP sorting multidimensional array issue

this is how my array look likes:

array(2) {
  'yamaha' =>
  array(2) {
    'r1' =>
    array(3) {
      [0] =>
      string(4) "2000"
      [1] =>
      string(4) "2001"
      [2] =>
      string(4) "1999"
    }
    'r2' =>
    array(1) {
      [0] =>
      string(4) "2000"
    }
  }
  'honda' =>
  array(3) {
    'ca-125' =>
    array(2) {
      [0] =>
      string(4) "1996"
      [1] =>
      string(4) "1995"
    }
    'cb-1000-r' =>
    array(4) {
      [0] =>
      string(4) "1993"
      [1] =>
      string(4) "1994"
      [2] =>
      string(4) "1995"
      [3] =>
      string(4) "1996"
    }
    'cb-1000-a' =>
    array(6) {
      [0] =>
      string(4) "2008"
      [1] =>
      string(4) "2009"
      [2] =>
      string(4) "2010"
      [3] =>
      string(4) "2011"
      [4] =>
      string(4) "2012"
      [5] =>
      string(4) "2013"
    }
  }
}

I would like to sort it after alphabetical order. If I do a asort($myarray). It will sort after the first key. So I will get honda and yamaha. Which is correct, but I would like to also sort it after the type of the brand: cb-1000-r and cb-1000-a(alphabetically) and the year in a descending order. Can someone help me with this ? Thank you

[UPDATE] This is my json. you can use json_decode

 {"B":{"r2":["1999","2001","2000"],"r1":["2000"]},"A":{"A1":["1996","1995"],"A3":["1993","1994","1995","1996"],"A2":["2008","2009","2010","2011","2012","2013"]}}

and I would like to get this json:

 {"A":{"r1":["2000"],"r2":["2001","2000","1999"]},"B":{"A1":["1996","1995"],"A2":["2013","2012","2011","2010","2009","2008"],"A3":["1996","1995","1994","1993"]}}

Advertisement

Answer

You’ll need to loop through your nested arrays and sort each level of them:

$arr = json_decode('{"B":{"r2":["1999","2001","2000"],"r1":["2000"]},"A":{"A1":["1996","1995"],"A3":["1993","1994","1995","1996"],"A2":["2008","2009","2010","2011","2012","2013"]}}', true);

ksort($arr);

foreach ($arr as &$arr1) {
    ksort($arr1);
    
    foreach ($arr1 as &$arr2) {
        rsort($arr2);
    }
}

var_dump($arr);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement