move a specific subarray to the top of a multidimensional array

I have an array of rows (from a mysql table)
And need to move to the top a subarray – i.e. a row – having id = $x
Tried a modified solution from here – without success

$st = $db->prepare("select id, nick from presto where id < 4");
$st->execute();
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
print_r($rows);

result

Array ( [0] => Array ( [id] => 52 [nick] => 5fb63a1a8bcbf ) [1] => Array ( [id] => 54 [nick] => 5fb63a1a75171 ) [2] => Array ( [id] => 59 [nick] => 5fb63a1a91e68 ) )

$x = 54;

foreach($rows as $key => $val){
    if($key['id'] == $x){  // line 155
        unset($rows[$key]);
        array_unshift($rows, $val);
    }
}

and getting Warning – Trying to access array offset on value of type int on line 155

please help

>Solution :

$key on line 155 is the index/iteration/position in the array/foreach, which is an integer, not an array. $val is your data array from each iteration.

Try this.

$x = 54;

foreach($rows as $key => $val){
    if($val['id'] === $x){  // line 155
        unset($rows[$key]);
        array_unshift($rows, $val);
    }
}

Leave a Reply