Fork me on GitHub

article

Use array_merge to reorder arrays

August 21, 2009 | PHP Scripting | 1 Comment

This one is pretty fun. Well, at least I think it is.

I was working with jQuery UI Sortables the other day and getting the reordered elements from jQuery back in to PHP for reordering via Ajax I ended up with an array whose elements matched the array keys of the array that I needed to order. Pretty standard fare. But I knew that there had to be a keen way to tackle the reordering process without going through some convoluted code. I was right. The way was the merge the two arrays.

The way array_merge works is if your array keys are non-numeric and that if the second given array has the same keys as the first given array the data from the second given array replaces the data in the first given array without reordering the first given array.

This was perfect since the two arrays will match perfectly in length and keys since they were built off the same data. This meany that all I had to do was take the new order data from jQuery Sortable, apply array_flip and merge the old ordered array in to the new order. Like so:

  1.  <?php
  2.  // my "original" array of data
  3.  $array = array(
  4.   'a135' => 'one',
  5.   '1b84' => 'two',
  6.   'd934' => 'three',
  7.  );
  8.  // the "new order" passed back to us from an outside source
  9.  $array2 = array(
  10.   'd934',
  11.   '1b84',
  12.   'a135'
  13.  );
  14.  // flip the keys and values of $array2
  15.  $array2f = array_flip($array2);
  16.  // merge the arrays and output
  17.  $r = array_merge($array2f,$array);
  18.  print_r($r);
  19.  ?>

This code outputs:

  1.  Array
  2.  (
  3.   [d934] => three
  4.   [1b84] => two
  5.   [a135] => one
  6.  )

So, the array is reordered without any hubbub. Nothing groundbreaking, just another way to reduce a few lines of code and not have to try and re-invent the wheel.