Search code examples
phparrayssortingarray-multisort

Sort an associative array the same way that another flat array is sorted


I have the following arrays:

$arr = array(
    'keyA' => 'valueA',
    'keyB' => 'valueB',
    'keyC' => 'valueC',
    'keyD' => 'valueD'
);

$order = array('3', '4', '1', '2');

I need to sort $arr based on $order so the output be

array(
    'keyC' => 'valueC',
    'keyD' => 'valueD', 
    'keyA' => 'valueA',
    'keyB' => 'valueB'   
);

Solution

  • $arr = array( 'keyA' => 'valueA', 'keyB' => 'valueB', 'keyC' => 'valueC', 'keyD' => 'valueD' );
    
    $order = array('3', '4', '1', '2');
    
    array_multisort($order, $arr);
    
    var_dump($arr);