Mikel
Mikel

Reputation: 27

Sort elements of an array depending on another array on PHP

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.

Upvotes: 1

Views: 37

Answers (2)

PHP Geek
PHP Geek

Reputation: 4033

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

Upvotes: 0

Rav
Rav

Reputation: 300

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

Upvotes: 1

Related Questions