skytorner
skytorner

Reputation: 415

Naturally sort an associative subarray by its keys in a descending direction

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

Upvotes: 0

Views: 83

Answers (3)

mickmackusa
mickmackusa

Reputation: 48070

Most simply, perform a descending natural key sort. Demo

krsort($array_by_lang['no'], SORT_NATURAL);

Upvotes: 0

voodoo417
voodoo417

Reputation: 12111

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

Upvotes: 2

Sougata Bose
Sougata Bose

Reputation: 31749

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

Upvotes: 1

Related Questions