phparrayssortingmultidimensional-arraycustom-sort

Sort a 2d array by its keys which relate to custom sorting values in another 2d array


I searched for my related topic, but didn't find a similar issue.

I have an array within an array and I have an array which I define as my ordering array.

$array1 = [
   "23456" => ["id" => 1, "info" => "info"],
   "78933" => ["id" => 1, "info" => "info"]
];

$orderarray = [
    ["id" => 78933],
    ["id" => 23456]
];

I would like to reorder $array1 keys by the value of $orderarray id.

So the first key in $array1 should be then 78933 and not 23456.

I know how to read the keys from $array1`.

foreach ($array1 as $key) {
   echo $key;
}

foreach ($orderarray as $key) {
    foreach ($key as $id => val) {
        echo $val;
    }
}

So how can I merge both foreach together the best way?


Solution

  • You can use a custom key-sort function using uksort()

    <?php
    
    $array = array(
       "23456" => array("id" => 1, "info" => "info"),
       "78933" => array("id" => 1, "info" => "info")
    );
    
    $orderarray = array(
        array("id" => 78933),
        array("id" => 23456)
    );
    
    function customSort($a, $b) {
        global $orderarray;
        $_a = 0; $_b = 0;
        foreach ($orderarray as $index => $order) {
            $oid = intval($order['id']);
            if ($oid == intval($a)) $_a = $index;
            if ($oid == intval($b)) $_b = $index;
        }
        if ($_a == $_b) {
            return 0;
        }
        return ($_a < $_b) ? -1 : 1;
    }
    
    uksort($array, "customSort");
    print_r($array);
    
    ?>