bey23 bey23 - 4 months ago 18
PHP Question

PHP - Order array associative by specific value

I'm looking for a way to order an array associative by a specific value, I'm not sure if it's possible. I tried it with

array_multisort()
and
usort()
functions, but I'm afraid that I can not get it.

Example:

$array[] = array('id' => 74215, 'type' => 'BOX');
$array[] = array('id' => 76123, 'type' => 'UNT');
$array[] = array('id' => 71231, 'type' => '');
$array[] = array('id' => 79765, 'type' => 'UNT');
$array[] = array('id' => 77421, 'type' => 'BOX');


If I want to order by 'BOX', then the array will be:

Array (
[0] => Array
(
[id] => 77421
[type] => 'BOX'
)
[1] => Array
(
[id] => 74215
[type] => 'BOX'
)
[2] => Array
(
[id] => 76123
[type] => 'UNT'
)
.
.
.


I could pass other string like 'UNT', and order by like that.
Is this possible??

Answer

I assume you want to "sort" by string match, first all those who match that string, after that all those that don't. Unless you have an archaic php version, this could work:

$sortvalue = 'BOX';
usort($array, function($a, $b) {
         if($a['type'] == $sortvalue) return -1;
         elseif($b['type'] == $sortvalue) return 1;
         else return 0;
    });

this should put any 'BOX' entry to the front of your array.

If all others shall be grouped, instead of return 0 do return $a['type'] < $b['type'].

Comments