按键的值对数组进行排序

时间:2015-11-04 10:20:43

标签: php arrays sorting key

我正在尝试按DESC顺序中的子键值对数组进行排序,但是我被卡住了。 我可以用ksort制作它,但它按升序排列..

这是我的数组:

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

我想要获得的是:

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

这可能吗?非常感谢

2 个答案:

答案 0 :(得分:2)

我认为,你需要“按键逆转自然排序”。只需使用enter image description hereDOMDocument(另请参阅array_multisort):

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

输出

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"
    }
   }
}       

答案 1 :(得分:1)

这可能会有所帮助 -

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

<强>输出

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