Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change orders of array?

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

I want to change the order to be 3,2,0,1

$a = array(3=>'d',2=>'c',0=>'a', 1=>'b');
like image 637
user198729 Avatar asked Feb 01 '10 08:02

user198729


1 Answers

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

  • uasort()— Sort an array with a user-defined comparison function and maintain index association
  • uksort()— Sort an array by keys using a user-defined comparison function
  • usort()— Sort an array by values using a user-defined comparison function

Based on Yannicks example below, you could do it this way:

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

would give

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

But like I said in the comments, if you do not tell us the rule by which to order the array or be more specific about your need, we cannot help you beyond this.

like image 183
Gordon Avatar answered Sep 29 '22 02:09

Gordon