while循环在一个数组?

时间:2012-06-20 14:14:54

标签: php arrays while-loop

我正在试图弄清楚我是否能够在数组中执行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循环,可能吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

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

"comments" => $comments -> fetchAll(PDO::FETCH_ASSOC)

答案 1 :(得分: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());
    );
}