为什么我的for循环显示两次相同的项目?

时间:2016-06-03 16:23:03

标签: php json

我正在尝试在JSON评论数组中显示每个项目。数组中有两条评论,但不是同时显示它们,而是显示相同的两条评论。

为什么会这样?

$response = curl_exec($curl);
$data = json_decode($response, true);

// Setup the Review for posting to the Mysql Database
// Loop through Reviews
for ($i=0; $i<count($data['reviews']); $i++) {
    $id = $data['reviews']['0']['id']; //  good
    $stars = $data['reviews']['0']['stars']; //good
    $title = $data['reviews']['0']['title'];
    $text = $data['reviews']['0']['text'];
    $createdAt = $data['reviews']['0']['createdAt'];
    $companyReply = $data['reviews']['0']['companyReply']['text'];
    $companyReplyDate = $data['reviews']['0']['companyReply']['createdAt'];

    // Do Mysql insert for each row

    // show this
    echo "id: " . $id . "</br>";
    echo "stars: " . $stars . "</br>";
    echo "title: " . $title . "</br>";
    echo "text: " . $text . "</br>";
    echo "Created: " . $createdAt . "</br>";
    echo "Reply: " . $companyReply . "</br>";
    echo "Reply Date: " . $companyReplyDate . "</br> </br>";
}

curl_close($curl);

1 个答案:

答案 0 :(得分:4)

这是因为您实际上并没有使用循环增量变量来获取不同的数组键。您只是反复选择['0']索引。相反,使用$i作为数组键,如下所示:

for ($i=0; $i<count($data['reviews']); $i++) {
    $id = $data['reviews'][$i]['id']; //  good
    $stars = $data['reviews'][$i]['stars']; //good
    $title = $data['reviews'][$i]['title'];
    $text = $data['reviews'][$i]['text'];
    $createdAt = $data['reviews'][$i]['createdAt'];
    $companyReply = $data['reviews'][$i]['companyReply']['text'];
    $companyReplyDate = $data['reviews'][$i]['companyReply']['createdAt'];
    // ... etc.