How to change the order of an array?

$a = array(0=>'a',1=>'b',2=>'c', 3=>'d');

I want to reorder 3,2,0,1:

$a = array(3=>'d',2=>'c',0=>'a', 1=>'b');
+3
source share
5 answers

If you want to change the order programmatically, look at the various array sorting functions in PHP , especially

  • uasort() - sort an array with a custom comparison function and maintain index association
  • uksort() - sorting an array using a custom comparison function
  • usort() - Sorting an array by values ​​using a custom comparison function

Based on the Yannicks example below, you can do it like this:

$a = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
$b = array(3, 2, 0, 1); // rule indicating new key order
$c = array();
foreach($b as $index) {
    $c[$index] = $a[$index];
}
print_r($c);

will give

Array([3] => d [2] => c [0] => a [1] => b)

, , , , .

+15

PHP , , .

:

$a = array(0=>'a',1=>'b',2=>'c', 3=>'d');
$order = array(3, 2, 0, 1);

foreach ($order as $index)
{
  echo "$index => " . $a[$index] . "\n";
}
+7
function reorder_array(&$array, $new_order) {
  $inverted = array_flip($new_order);
  uksort($array, function($a, $b) use ($inverted) {
    return $inverted[$a] > $inverted[$b];
  });
}

$a = array(0=>'a',1=>'b',2=>'c', 3=>'d');
reorder_array($a, array(3, 2, 0, 1));

var_dump($a);

Result:

Array ( [3] => d [2] => c [0] => a [1] => b )
+5
source

The easiest way to do this is in a uksort()more functional way:

$a = ['a','b','c','d'];
$order = [3, 2, 0, 1];

uksort($a, function($x, $y) use ($order) {
    return array_search($x, $order) > array_search($y, $order);
});

print_r($a); // [3 → d, 2 → c, 0 → a, 1 → b]
0
source

that's how

krsort($a);
-3
source

Source: https://habr.com/ru/post/1730833/


All Articles