2012-06-20 125 views
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循环while循环,这可能吗?

谢谢!

+5

你试过了吗? –

+0

只需尝试一下,看看你会得到一个语法错误,并尝试一种不同的方法。短:不,这是不可能的。 – Yoshi

+1

它的可能,除非你尝试 – Khurram

回答

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()); 
    ); 
} 
+1

+1和答案的完整脚本的例子,和其他方法的方法 – hellomello

2

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

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

+1为简单例子。谢谢! – hellomello