使用foreach的Echo数据数据

时间:2017-03-10 19:39:47

标签: php json

我有一个带有以下代码的MySQL查询:

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

“守则”有效,但我只收到一个结果。

我的输出:

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

foreach代码中的错误是什么?

1 个答案:

答案 0 :(得分:2)

每次循环时都会覆盖$ array_s。

试试这个

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

我在这里做的是:我设置了一个$ i计数器,所以每当你将值传递给数组时,我都会指定它的位置。在此之前,每次循环时都会覆盖数组,因此结果将不再是查询提取的最后一项。