0

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?

Marcel Emblazoned
  • 533
  • 1
  • 4
  • 14

1 Answers1

0

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;
});
NDM
  • 6,415
  • 3
  • 33
  • 49