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

5
  • Can you please check this url stackoverflow.com/questions/5312879/… Commented Nov 22, 2022 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". Commented Nov 22, 2022 at 11:55
  • @jspit - are you sure ? I'm getting rows having id as 1, 2, or 3. What's the problem ? Commented Nov 22, 2022 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. Commented Nov 22, 2022 at 18:18
  • @jspit - you're right, that's a mistake, but it's already solved, thanks a lot Commented Nov 23, 2022 at 9:36

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.