noganno
2/26/2016 - 3:15 AM

http://gostash.it/en/stashes/331

<?php 
function orderByKeys(array $array, array $keys)
{
    foreach ($keys as $k => $v) {
        if (!array_key_exists($v, $array)) {
            unset($keys[$k]);
        }
    }

   return array_replace(array_flip($keys), $array);
}

$data = [
    'orange' => 'orange',
    'apple' => 'tasty',
    'carpet' => 'old',
    'car' => 'fast',
];

$result = orderByKeys($data, ['car', 'carpet']);

//Would result in:

$data = [
    'car' => 'fast',
    'carpet' => 'old',
    'orange' => 'orange',
    'apple' => 'tasty',    
];