尝试在同一个JSON对象中输出JSON值

时间:2018-03-31 23:26:45

标签: php json

现在我的php文件输出JSON,如下所示:

[
  {"category":142,"review_id":92},
  {"category":383,"review_id":353},
  {"category":203,"review_id":149},
  {"category":239,"review_id":355},
  {"category":239,"review_id":201},
  {"category":183,"review_id":59},
  {"category":183,"review_id":62}
]

但我希望它输出如下:

[
  {"category":142,"review_id":92},
  {"category":383,"review_id":353},
  {"category":203,"review_id":149},
  {"category":239,"review_id":355,"review_id":201},
  {"category":183,"review_id":59, "review_id":62}
]

我希望category出现在同一个对象中,而不是重复review_ids个数字。你能告诉我怎么能这样做吗?

这是我的代码:

$user_id = "21";

//Select all related info in the review_shared table 
//where the contact_id column is equal to $user_id.

//a value in the contact_id column means a review is shared with a person, $user_name,
//who owns that number, $user_id
$sql = "SELECT * FROM review_shared WHERE contact_id = ?";
$stmt2 = $con->prepare($sql) or die(mysqli_error($con));
$stmt2->bind_param('i', $user_id) or die ("MySQLi-stmt binding failed ".$stmt2->error);
$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
$result2 = $stmt2->get_result();

$results = array();

//fetch all rows associated with the respective contact_id value
//in review_shared table
while ($row = $result2->fetch_assoc()) {

    //get the corresponding cat_id in the row
    $cat_id = $row["cat_id"];

    //get the corresponding review_id in the row
    $review_id = $row["review_id"];

    //make an array called $results
    $results[] = array(
            //get the corresponding cat_name in the row
            'category' => $row['cat_id'],  
            'review_id' => $review_id,
        );
}

echo json_encode($results);

我尝试的代码如下:

$review_id_results[] = array('review_id' => $review_id);

但不知道如何正确地做到这一点,并且不确定该怎么做。

1 个答案:

答案 0 :(得分:2)

您不能在对象上拥有重复的礼节。您真正想要的是将您的所有review_ids列为数组。像这样:

$results = array();

//fetch all rows associated with the respective contact_id value
//in review_shared table
while ($row = $result2->fetch_assoc()) {

    //get the corresponding cat_id in the row
    $cat_id = $row["cat_id"];

    //get the corresponding review_id in the row
    $review_id = $row["review_id"];

    //make an array called $results
    $results[$row['cat_id']][] = $review_id; 
}

$jsonData = array_map(function($catId) use ($results) {
    return [
        'category' => $catId,
        'review_ids' => $results[$catId]
    ];
}, array_keys($results));

echo json_encode($jsonData);

最终结果将是

[{"category":123,"review_ids":[1,2]},{"category":456,"review_ids":[3]}]