Php:你能告诉我为什么只有我的最后一个数组值被回应?

时间:2018-04-14 08:21:03

标签: php arrays foreach

它仅回显了值review_id的最后76,如:

[{
    "category":"whatever",
    "name":"whatever",
    "phone":"whatever",
    "comment":"whatever",
    "reviewid":76
}]

但它应该回应:

[
    {
        "category":"whatever",
        "name":"whatever",
        "phone":"whatever",
        "comment":"whatever",
        "reviewid":32
    },
    {
        "category":"whatever",
        "name":"whatever",
        "phone":"whatever",
        "comment":"whatever",
        "reviewid":76
    }
]

这是我的代码。我看了SO上的其他帖子,看不出我做的那么不同。

 <?php
    require('file.php');
    $ReviewIDs = array("32","76");
    foreach($ReviewIDs as $ReviewID) {
        $sql2 = "SELECT * FROM review WHERE review_id = ?";
        $stmt2 = $con->prepare($sql2) or die(mysqli_error($con));
        $stmt2->bind_param('i', $ReviewID) or die ("MySQLi-stmt binding failed ".$stmt2->error);
        $stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
        $result2 = $stmt2->get_result();
        $results = array();
        while($row = mysqli_fetch_array($result2)) {//make an array called $results
            $results[] = array(
                'category' => $row['cat_name'],
                'name' => $row['name'],
                'phone' => $row['phone'],
                'comment' => $row['comment'],
                'reviewid' => $row['review_id'],
            );
        }
    }
    $json = json_encode($results);
    echo $json;
?>

1 个答案:

答案 0 :(得分:4)

$results = array(); 必须foreach开始之前定义。 否则,每次foreach次迭代都会覆盖