maria maria - 6 months ago 18
PHP Question

Sort multidimentional array PHP by ids

Im trying to sort an multidimentional array based on a array in the order i would like it to appear in.

the

$lookingfor
array contains the order i would like it to appear, while
$avaliableArray
contains the whole multidimentional array. Would like the result in the example code called
$resultarray


How would i do this, based on the
id
of the elements in
$avaliableArray
?

code:

$avaliableArray = array(
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-1"),
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-4"),

array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-8")
);


$lookingFor = array(1,8,4);


looking for result:

$resultArray = array(
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-1"),
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-8"),

array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-4")
);

Answer

Use usort() and apply proper id to $lookingFor same as array value.

$avaliableArray = array(       
         array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-1"),
                array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-4"),

                array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-8")
);


$lookingFor = array("testid-1","testid-2","testid-8");
usort($avaliableArray, function ($a, $b) use ($lookingFor) {
    $pos_a = array_search($a['id'], $lookingFor);
    $pos_b = array_search($b['id'], $lookingFor);
    return $pos_a - $pos_b;
});
echo "<pre>";
print_r($avaliableArray);

Output

Array
(
    [0] => Array
        (
            [name] => Banken
            [site] => bank
            [avaliable] => 1
            [type] => site
            [id] => testid-1
        )

    [1] => Array
        (
            [name] => Banken
            [site] => bank
            [avaliable] => 1
            [type] => site
            [id] => testid-2
        )

    [2] => Array
        (
            [name] => Banken
            [site] => bank
            [avaliable] => 1
            [type] => site
            [id] => testid-8
        )

)