简体   繁体   中英

Echo Array data with foreach

I have a MySQL Query with following code:

$stmt_offer = $pdo->query("SELECT * FROM `offers` WHERE `fs` = '1' ORDER BY `id` DESC LIMIT 15");


  foreach ($stmt_offer as $row):
    $array_s['hbid']        = $row['ang_id'];
    $array_s['title']       = $row['titel'];
    $array_s['size']        = $row['qm'];
    $array_s['description'] = $row['beschreibung'];
  endforeach;

  $array_object['response'] = $array_s;
  $array_offer['offer']     = $array_object;

  echo json_encode($array_offer);

The Code works finde, but i get only one result back.

My Output:

{
 "offer":
  {
   "response":
    {
     "hbid":"1234567",
     "title":"Test",
     "size":"100",
     "description":"my_description"
  }
 }
}

What's the error in the foreach code?

You're overwriting $array_s everytime you loop.

Try this instead

$stmt_offer = $pdo->query("SELECT * FROM `offers` WHERE `fs` = '1' ORDER BY `id` DESC LIMIT 15");


 $i = 0;
 foreach ($stmt_offer as $row):
   $array_s[$i]['hbid']        = $row['ang_id'];
   $array_s[$i]['title']       = $row['titel'];
   $array_s[$i]['size']        = $row['qm'];
   $array_s[$i]['description'] = $row['beschreibung'];
   $i++;
 endforeach;

 $array_object['response'] = $array_s;
 $array_offer['offer']     = $array_object;

 echo json_encode($array_offer);

What Iam doing here is: I've set a $i counter, so everytime you'll loop passing the values to the array, I'm specifying what position it will be. Before, you were overwriting the array everytime you loop, so the result would aways be the last item your query has fetched.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM