小编典典

PHP的回声JSON在foreach循环

ajax

我有这样的1,2,3产品ID $product_ids

$product_ids = explode(',', $product_ids);
$product_ids = array_filter($product_ids);

foreach ($product_ids as $key => $product_id) {

      $sth = $this->db->prepare("SELECT * FROM products Where id =:id ");
      $sth->execute(array( ':id' => $product_id ));
      $final_data = $sth->fetchAll();

      echo json_encode($final_data);
}

json该如何在for循环回显中使用此代码设置格式,请问json还有其他方法吗


阅读 303

收藏
2020-07-26

共1个答案

小编典典

    $product_ids = explode(',', $product_ids);
    $product_ids = array_filter($product_ids);
    $final_data = array();
    foreach ($product_ids as $key => $product_id) {

          $sth = $this->db->prepare("SELECT * FROM products Where id =:id ");
          $sth->execute(array( ':id' => $product_id ));
          $final_data[$product_id] = $sth->fetchAll();


    }
    echo json_encode($final_data);
2020-07-26