简体   繁体   中英

Sort array by the value of the key

i'm trying to sort an array by the value of a sub-key in DESC order but I'm stuck. I've could make it with ksort but it was in ascending order..

Here's my array :

 array_by_lang => array(
        [no] => array(
             [3-1] => array(//some informations),
             [3-10] => array(//informations),
             [3-7] => array(//informations),
             [5-1] => array(//informations)
        )
 )

what i want to obtain is something like :

  array_by_lang => array(
        [no] => array(
             [5-1] => array(//informations),
             [3-10] => array(//some informations),
             [3-7] => array(//informations),
             [3-1] => array(//informations)
        )
 )

Is that possible ? Thanks a lot

I think, you need "reversing natural sort by key". Just with array_multisort and array_reverse (see also natsort ):

    $array_by_lang = array(
        'no' => array(
            '3-1'  => array('info_1'),
            '3-10' => array('info_2'),
            '3-7'  => array('info_3'),
            '5-1'  => array('info_4'),
        )
    );


    array_multisort(array_keys($array_by_lang['no']),SORT_NATURAL, $array_by_lang['no']);
    $array_by_lang['no'] = array_reverse($array_by_lang['no']); // reverse natural order - "DESC"
    var_dump($array_by_lang);

Output

array(1) {
  ["no"]=>
    array(4) {
    ["5-1"]=>
      array(1) {
        [0]=>
        string(6) "info_4"
    }
    ["3-10"]=>
      array(1) {
        [0]=>
        string(6) "info_2"
    }
    ["3-7"]=>
      array(1) {
        [0]=>
        string(6) "info_3"
    }
    ["3-1"]=>
      array(1) {
       [0]=>
       string(6) "info_1"
    }
   }
}       

This might help -

$a = array(
'3-1' => array('//some informations'),
'3-10' => array('//informations'),
'3-7' => array('//informations'),
'5-1' => array('//informations')
);

## Array for keys
$temp= array();
foreach(array_keys($a) as $v) {
    $t = explode('-', $v);
    $temp[$t[0]][] = $t[1]; 
}

## Sort the keys
foreach($temp as &$ar) {
   rsort($ar);
}
krsort($temp);

## Final array
$final= array();
foreach($temp as $k => $f) {
   foreach($f as $v) {
       $key = $k . '-' . $v;
       $final[$key] = $a[$key];
   }
}

var_dump($final);

Output

array(4) {
  ["5-1"]=>
  array(1) {
    [0]=>
    string(14) "//informations"
  }
  ["3-10"]=>
  array(1) {
    [0]=>
    string(14) "//informations"
  }
  ["3-7"]=>
  array(1) {
    [0]=>
    string(14) "//informations"
  }
  ["3-1"]=>
  array(1) {
    [0]=>
    string(19) "//some informations"
  }
}

DEMO

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