1

How could I sort an array depending on another array, considering that one array has fewer elements than another?

// correct order
$order = ['aaa', 'ccc', 'bbb'];

// my array
$items = [
    'key_one' => 'ccc',
    'key_two' => 'aaa',
    'key_three' => 'ccc',
    'key_four' => 'bbb',
    'key_five' => 'aaa'
];

// the result I want
$items = [
    'key_two' => 'aaa',
    'key_five' => 'aaa'
    'key_one' => 'ccc',
    'key_three' => 'ccc',
    'key_four' => 'bbb'
];

I've tried with array_merge and array_combine but having different number of keys I don't know how to do it.

2 Answers 2

1

Use the following code:

 $items = [
    'key_one' => 'ccc',
    'key_two' => 'aaa',
    'key_three' => 'ccc',
    'key_four' => 'bbb',
    'key_five' => 'aaa'
];

function list_cmp($a, $b) 
{ 
 $order = ['aaa', 'ccc', 'bbb'];

  foreach($order as $key => $value) 
    { 
      if($a==$value) 
        { 
          return 0; 
          break; 
        } 

      if($b==$value) 
        { 
          return 1; 
          break; 
        } 
    } 
} 

uasort($items, "list_cmp"); 

print_r($items);
Sign up to request clarification or add additional context in comments.

1 Comment

The result is : Array ( [key_two] => aaa [key_five] => aaa [key_one] => ccc [key_three] => ccc [key_four] => bbb )
0
try to use the code below

$items = [
        'key_one' => 'ccc',
        'key_two' => 'aaa',
        'key_three' => 'ccc',
        'key_four' => 'bbb',
        'key_five' => 'aaa'
    ];
    $order = ['aaa', 'ccc', 'bbb'];
    $newArray = [];
    foreach ($order as $order) {
        foreach($items as $key => $item){
            if($item == $order){
                $newArray[$key] = $item;
            }
        }
    }
    print_r($newArray);

2 Comments

The problem with asort is that it orders them alphabetically, not according to the order that I have established. asort returns aaa, bbb, ccc and not aaa, ccc, bbb.
fine you need to append the array by another array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.