2016-05-23 14 views
5

Come posso ordinare in modo approfondito un array multidimensionale e mantenere le chiavi?PHP array_multisort - come mantenere i valori chiave?

$array = [ 
    '2' => [ 
     'title' => 'Flower', 
     'order' => 3 
    ], 
    '3' => [ 
     'title' => 'Rock', 
     'order' => 1 
    ], 
    '4' => [ 
     'title' => 'Grass', 
     'order' => 2 
    ] 
]; 

foreach ($array as $key => $row) { 
    $items[$key] = $row['order']; 
} 

array_multisort($items, SORT_DESC, $array); 

print_r($array); 

risultato:

Array 
(
    [0] => Array 
     (
      [title] => Flower 
      [order] => 3 
     ) 

    [1] => Array 
     (
      [title] => Grass 
      [order] => 2 
     ) 

    [2] => Array 
     (
      [title] => Rock 
      [order] => 1 
     ) 

) 

Quello che sto dopo:

Array 
(
    [2] => Array 
     (
      [title] => Flower 
      [order] => 3 
     ) 

    [4] => Array 
     (
      [title] => Grass 
      [order] => 2 
     ) 

    [3] => Array 
     (
      [title] => Rock 
      [order] => 1 
     ) 

) 

Tutte le idee?

+3

controllo questo: [http://stackoverflow.com/questions/23740747/array-multisort-with-maintaining-numeric-index-association](http://stackoverflow.com/questions/23740747/array -multisort-con-mantenimento-numerico-index-associazione) –

risposta

1

Può essere questo è quello che stai cercando: Online Example

Mantenere le chiavi degli array, ordinare con la colonna dell'ordine e combinarli ancora.

$keys = array_keys($array); 
array_multisort(
    array_column($array, 'order'), SORT_DESC, SORT_NUMERIC, $array, $keys 
); 
$array = array_combine($keys, $array); 
echo '<pre>'; 
print_r($array); 
5

Si può provare uasort:

uasort($array, function ($a, $b) { return $b['order'] - $a['order']; }); 

tuo codice:

<?php 

$array = [ 
    '2' => [ 
     'title' => 'Flower', 
     'order' => 3 
    ], 
    '3' => [ 
     'title' => 'Rock', 
     'order' => 1 
    ], 
    '4' => [ 
     'title' => 'Grass', 
     'order' => 2 
    ] 
]; 

uasort($array, function ($a, $b) { return $b['order'] - $a['order']; }); 

print_r($array); 

Demo