Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ) )

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading