0

I'm trying to figure out if I'm able to do a while loop inside an array

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

There's a while loop within the comments, is that possible?

Thanks!

4
  • simply try it, see that you'll get a syntax error and try a different approach. Short: no it's not possible. Commented Jun 20, 2012 at 14:17
  • @Khurram Is that a Schrödinger reference? Commented Jun 20, 2012 at 14:21
  • @deceze it came from my own sense of understanding :-D, i didn't know about that great scientist before, thx for sharing his name and thx to wiki , cheers Commented Jun 20, 2012 at 14:35
  • @JohnConde I did try it. I ment to ask which approach should I take to accomplish something similar. Commented Jun 20, 2012 at 17:10

2 Answers 2

2

The way you write it is not possible, but there is a simple solution:

"comments" => $comments -> fetchAll(PDO::FETCH_ASSOC)
Sign up to request clarification or add additional context in comments.

Comments

1

Since you are inserting it into a JSON String, do it like this:

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

Otherwise, you could call implode on the comments:

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 Comment

+1 and answer for full script of example, and other method approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.