foreach循环中的php echo json

时间:2012-11-12 10:58:31

标签: php ajax json

我在$product_ids

中有这样的1,2,3产品ID
$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 for echo echo json无法正常工作是否有其他方式plz help

1 个答案:

答案 0 :(得分:4)

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