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

2
  • 1
    You cannot have more than one item with same key in a php array. For e.g.ccc Commented Mar 12, 2014 at 10:53
  • In stackoverflow.com/questions/17364127/… scroll down to Sorting into a manual, static order Commented Mar 12, 2014 at 10:57

2 Answers 2

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

?>
Sign up to request clarification or add additional context in comments.

Comments

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
)
.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.