0

I have a rather complicated issue that's probably related to array_splice but I can't figure it out. Here's an example of the array I have:

array(
 'a' => 'Element A',
 'b' => 'Element B',
 'c' => 'Element C',
 'd' => 'Element D',
 'e' => 'Element E'
);

What I want to do is reorder the array based on the key I select, say "c", such that the end result is:

array(
 'c' => 'Element C',
 'd' => 'Element D',
 'e' => 'Element E',
 'a' => 'Element A',
 'b' => 'Element B'
);

It basically moves the selected key to the front, while keeping the ordering intact. Any help is greatly appreciated!

Mike Feng
  • 803
  • 2
  • 9
  • 19
  • So you have they key `c` as input and you just want to move it to the top? – Rizier123 Jul 27 '15 at 15:29
  • 1
    have you tried using [this](http://stackoverflow.com/a/6933432/4786273) (to remove last element) and [this](http://stackoverflow.com/a/1371021/4786273) or [this](http://stackoverflow.com/a/12124318/4786273) (to add it at the beginning of the array) ? – Random Jul 27 '15 at 15:44

3 Answers3

2

array_search() will get the offset of c in array_keys() from the array. Then array_slice() that and array_merge() with the modified original array:

$array = array_merge(array_slice($array, array_search('c', array_keys($array)), null),
                     $array);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

Not the most beautfiul solution but it works

$arr = array(
 'a' => 'Element A',
 'b' => 'Element B',
 'c' => 'Element C',
 'd' => 'Element D',
 'e' => 'Element E'
);

function doIt($key, &$arr)
{
   $tmp  = array();
   $tmp2 = array();
   $flag = false;
   foreach($arr as $k => $v) {
      if($k == $key) {
         $flag = true;
      }
      if($flag) {
        $tmp2[$k] = $v;
      } else {
        $tmp[$k] = $v;
      }
   }
   $arr = array_merge($tmp2, $tmp);
}
doIt('c', $arr);
print_r($arr);

Output:

Array
(
    [c] => Element C
    [d] => Element D
    [e] => Element E
    [a] => Element A
    [b] => Element B
)

Fiddle

Robert
  • 19,800
  • 5
  • 55
  • 85
-1

You should see the doc of sort() function : http://php.net/manual/en/function.sort.php

in "User Contributed Notes" you will probably found the perfect function for your probleme !

  • Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Rohit Gupta Aug 22 '15 at 07:52