1

I would like to sort the array so that if a given value ($first_in_array) = 'brand' value, the array would become the first it the queue. In the given example an array with index[1] should appear like at index[0].

$first_in_array = 'PickMeFirst';

$data = Array(
    0 => array(
        'articleId'     => 5478,
        'articleName'   => 'Demo artcle name 1',
        'brand'         => 'Unbranded',
       ),
    1 => array(
        'articleId'     => 8785,
        'articleName'   => 'Demo artcle name 2',
        'brand'         => 'PickMeFirst',
       ),
    2 => array(
        'articleId'     => 1258,
        'articleName'   => 'Demo artcle name 3',
        'brand'         => 'None',
       ),
); 
mufazmi
  • 720
  • 4
  • 13
  • 30
Jurgen
  • 119
  • 8
  • Does this answer your question? [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – El_Vanja May 02 '21 at 14:20
  • Look for `usort` examples. All you need to do is say that when the brand matches, that element should come before the other one. – El_Vanja May 02 '21 at 14:22

2 Answers2

2

The accepted answer moves your value to the first position. However, it also moves other values. Which is absolutely fine, if that is not a concern for you. You could also do the following, which will move your value to the front, but leave other values in place.

usort($data, function ($a, $b) use ($first_in_array) {
    if($b['brand'] === $first_in_array) {
        return 1;
    } else {
        return 0;
    }
});
Andrew Hardiman
  • 840
  • 12
  • 25
1

You can use the callback function of usort and first deal with the case where exactly one of the two matches that specific string. In all other cases use the normal strcmp result:

usort($data, function ($a, $b) use ($first_in_array)  {
    return ($b["brand"] === $first_in_array) - ($a["brand"] === $first_in_array)
        ?: strcmp($a["brand"], $b["brand"]);
});
trincot
  • 211,288
  • 25
  • 175
  • 211