0

我试图弄清楚我是否能够在数组内进行 while 循环

while($row = $retail -> fetch(PDO::FETCH_ASSOC)){

$json['data'][] = array(

'id'=>$row['idretailers'],
"category"=>$row['category'],
"headline"=>$row['headline'],
'price'=> array ("full_price" => $row['price']),
'description'=>$row['description'],
"comments" => array(
while($row_c = $comments -> fetch(PDO::FETCH_ASSOC)){

 // more items  
})
);
}

评论中有一个while循环,这可能吗?

谢谢!

4

2 回答 2

2

您编写它的方式是不可能的,但是有一个简单的解决方案:

"comments" => $comments -> fetchAll(PDO::FETCH_ASSOC)
于 2012-06-20T14:20:52.033 回答
1

由于您要将其插入 JSON 字符串,因此请执行以下操作:

while($row = $retail -> fetch(PDO::FETCH_ASSOC)){

    $json['data'][] = array(

        "id"=>$row['idretailers'],
        "category"=>$row['category'],
        "headline"=>$row['headline'],
        "price"=> array ("full_price" => $row['price']),
        "description"=>$row['description'],
        "comments" => $comments->fetchAll()
    );
}

否则,您可以在评论中调用implode :

while($row = $retail -> fetch(PDO::FETCH_ASSOC)){

    $json['data'][] = array(

        "id"=>$row['idretailers'],
        "category"=>$row['category'],
        "headline"=>$row['headline'],
        "price"=> array ("full_price" => $row['price']),
        "description"=>$row['description'],
        "comments" => implode("\n", $comments->fetchAll());
    );
}
于 2012-06-20T14:49:24.157 回答