使用另一个数组对多维数组进行排序

时间:2017-01-26 08:07:25

标签: php arrays sorting multidimensional-array

我有以下数组(因此顺序,它不完全是增量的)

array ( 4334 => '4334',
        4335 => '4335',
        4333 => '4333',
        4338 => '4338',
)

这个数组

array ( 
        'alpha' => array ( 4333 => '4333', 'objects' => array ( ), ),
        'bar' => array ( 4338 => '4338', 'objects' => array ( ), ),
        'charlie' => array ( 4334 => '4334', 'objects' => array ( ), 
        'delta' => array ( 4335 => '4335', 'objects' => array ( ), ), ),
)

我们可以看到,第二个数组包含4个数组。里面又有一个id,例如alpha4333。如何对第二个数组进行排序,而顺序与第一个普通数组的顺序相同?

最终的排序应该是:

array (
        'charlie' => array ( 4334 => '4334', 'objects' => array ( ),
        'delta' => array ( 4335 => '4335', 'objects' => array ( ), ), ),
        'alpha' => array ( 4333 => '4333', 'objects' => array ( ), ),
        'bar' => array ( 4338 => '4338', 'objects' => array ( ), ),
)

1 个答案:

答案 0 :(得分:1)

这对我有用:

function elementScore($element, $sorting_array)
{
    // get the first element and find its position in the sorting array.
    return $sorting_array[intval(array_values($element)[0])];
}

$array1 = array ( 4334 => '4334',
    4335 => '4335',
    4333 => '4333',
    4338 => '4338',
);
// get the values without the keys and flip keys and values.
$sorting_array = array_flip(array_values($array1));

$array2 = array (
    'alpha' => array ( 4333 => '4333', 'objects' => array ( ), ),
    'bar' => array ( 4338 => '4338', 'objects' => array ( ), ),
    'charlie' => array ( 4334 => '4334', 'objects' => array ( ),
        'delta' => array ( 4335 => '4335', 'objects' => array ( ), ), ),
);

// sort based on the score function.
uasort($array2, function ($a, $b) use (&$sorting_array) {
    return elementScore($a, $sorting_array) > elementScore($b, $sorting_array);
});