Marcel Emblazoned Marcel Emblazoned - 4 months ago 16
PHP Question

PHP, Sort/merge multidimensional array by other (smaller) array

I have this array:

$original=[];
$original[]=['value'=>'a','count'=>10];
$original[]=['value'=>'b','count'=>15];
$original[]=['value'=>'c','count'=>23];
$original[]=['value'=>'d','count'=>40];
$original[]=['value'=>'e','count'=>25];


And this array that contains the items that should be at the beginning of the $original array:

$sort=['d','c'];


So the result should eventually be:

[
(int) 0 => [
'value' => 'd',
'count' => (int) 40
],
(int) 1 => [
'value' => 'c',
'count' => (int) 23
],
(int) 2 => [
'value' => 'a',
'count' => (int) 10
],
(int) 3 => [
'value' => 'b',
'count' => (int) 15
],
(int) 4 => [
'value' => 'e',
'count' => (int) 25
],
]


Using a simple for loop this is doable, but is there a nice way to do this?

NDM NDM
Answer

You could do this using usort

$priority = ['d', 'c'];
usort($original, function ($a, $b) use ($priority) {

    $prioA = array_search($a['value'], $priority);
    $prioB = array_search($b['value'], $priority);

    if ($prioA !== false && $prioB !== false) {
        if ($prioA < $prioB) return -1;
        return 1;
    }
    if ($prioA !== false) return -1;
    if ($prioB !== false) return 1;

    return 0;
});
Comments