0

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

provance
  • 877
  • 6
  • 10
  • Can you please check this url https://stackoverflow.com/questions/5312879/moving-array-element-to-top-in-php – Lokendra Singh Panwar Nov 22 '22 at 11:44
  • A query with "where id < 4" can never give a result like you show. If you want to exclude certain id you can already do that with SQL "NOT IN". – jspit Nov 22 '22 at 11:55
  • @jspit - are you sure ? I'm getting rows having `id` as `1`, `2`, or `3`. What's the problem ? – provance Nov 22 '22 at 16:04
  • And where does the ID 54 that you want to bring to the top come from? Sample data and code are inconsistent. – jspit Nov 22 '22 at 18:18
  • @jspit - you're right, that's a mistake, but it's already solved, thanks a lot – provance Nov 23 '22 at 09:36

1 Answers1

1

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