dpbl91234
2011-08-30 19:20
浏览 49

如何使用json回显数组?

My code does not seem to return JSON for $_GET['fruitVariety'], any idea why? My DB is correctly set up.

It's like json_encode can only echo 1 array.

$rows = array();

if(isset($_GET['fruitName'])) {
    $stmt = $pdo->prepare("SELECT DISTINCT variety FROM fruit WHERE name = ? ORDER BY variety");
    $stmt->execute(array($_GET['fruitName']));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

if(isset($_GET['fruitVariety'] )) {
    $stmt = $pdo->prepare("SELECT DISTINCT fruittype FROM fruit WHERE name = ? ORDER BY fruittype");
    $stmt->execute(array($_GET['fruitVariety']));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

echo json_encode($rows);

图片转代码服务由CSDN问答提供 功能建议

我的代码似乎没有为 $ _ GET ['fruitVariety'] 返回JSON, 任何想法为什么? 我正确设置了数据库。

这就像json_encode只能回显1个数组。

  $ rows = array(); 
 
if(isset($ _ GET)  ['fruitName'])){
 $ stmt = $ pdo-> prepare(“SELECT DISTINCT variety FROM fruit WHERE name =?ORDER BY variety”); 
 $ stmt-> execute(array($ _ GET [  'fruitName'])); 
 $ rows = $ stmt-> fetchAll(PDO :: FETCH_ASSOC); 
} 
 
if(isset($ _ GET ['fruitVariety'])){
 $ stmt =  $ pdo-> prepare(“SELECT DISTINCT fruittype FROM fruit WHERE name =?ORDER BY fruittype”); 
 $ stmt-> execute(array($ _ GET ['fruitVariety'])); 
 $ rows = $  stmt-> fetchAll(PDO :: FETCH_ASSOC); 
} 
 
echo json_encode($ rows); 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanaoyuan7202 2011-08-30 19:22
    已采纳

    You're overriding the value you put in $rows after the first query. You should do :

     $rows[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    

    The brackets ([]) are very important ! You can find more information about the proper syntax in the PHP documentation.

    And actually, I think you only have the values for fruitVariety and not for fruitName ;)

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题