0

is it possible to sort an array by keys using an custom order ? i have an array with strings that represent the order.

$order = array('ccc','aaa','xxx','111');
$myarray = array('ccc' => 'value1','aaa' => 'value2','xxx' => 'value3',
                     'BBB' => 'value11','ddd' => 'value31')

now i want the array to be sorted with the elemnts with the key 'ccc' at the first position, the nthe elements with the key aaa ... and at the end should be the elements that are not in the sortlist.

is this possible ?

edit: the second 'CCC' was my fault - sorry

user1121575
  • 390
  • 1
  • 4
  • 19
  • 1
    You cannot have more than one item with same `key` in a php array. For e.g.`ccc` – SajithNair Mar 12 '14 at 10:53
  • In http://stackoverflow.com/questions/17364127/reference-all-basic-ways-to-sort-arrays-and-data-in-php scroll down to **Sorting into a manual, static order** – Barmar Mar 12 '14 at 10:57

2 Answers2

0

I was just having a think about this as I was having a similar issue with array_multisort() and ksort().

However in your case if the snippet of code is correct, will not be possible as the second 'ccc' key with a value of 'value11' will overwrite the previous one.


php > $myarray = array('ccc' => 'value1','aaa' => 'value2','xxx' => 'value3','ccc' => 'value11','ddd' => 'value31');
php > print_r($myarray);
Array
(
    [ccc] => value11
    [aaa] => value2
    [xxx] => value3
    [ddd] => value31
)
.
vrooze
  • 68
  • 7
0

See this in action https://eval.in/118734

<?php

$order = array('ccc','xxx','aaa','111');
$myarray = array('ccc' => 'value1','aaa' => 'value2','xxx' => 'value3',
                     'ddd' => 'value31');

$temp = array();
foreach($order as $o) {
   if(array_key_exists($o, $myarray)) {
       $temp[$o] = $myarray[$o];
   }
}

$new = array_merge($temp, $myarray);
print_r($new);

?>
SajithNair
  • 3,867
  • 1
  • 17
  • 23