【问题标题】:How can I merge these two JSON arrays? [duplicate]如何合并这两个 JSON 数组? [复制]
【发布时间】:2018-09-13 07:52:14
【问题描述】:

我的 php 生成两个 JSON 数组,例如:

[{"category":183,"private_review_ids":[63,59,62]},
{"category":363,"private_review_ids":[331]}, 
{"category":371,"private_review_ids":[341]},
{"category":379,"private_review_ids":[350]}]
[{"category":363,"public_review_ids":[331]},
{"category":373,"public_review_ids":[343]},
{"category":384,"public_review_ids":[356]},
{"category":183,"public_review_ids":[347]}]

我怎样才能合并这些数组,使它们只是下面形式的一个数组。这不仅仅是合并数组 - 它是可能将值从 JSON 对象中的一个键 (public_review_ids) 转移到另一个键 (private_review_ids)。这是我想要的 JSON 数组的形式:

[{"category":183,"private_review_ids":[63,59,62],"public_review_ids":[347] },
{"category":363,"private_review_ids":[331],"public_review_ids":[]}, 
{"category":371,"private_review_ids":[341],"public_review_ids":[]},
{"category":379,"private_review_ids":[350]},"public_review_ids":[]},
{"category":373,"private_review_ids":[],"public_review_ids":[343]},
{"category":384,"private_review_ids":[],"public_review_ids":[356]}]

如您所见,如果值同时存在于private_review_idspublic_review_ids 中,它应该只出现在private_review_ids 键中。

我尝试使用array_uniquearray_merge,但没有成功,真的。

这是我的代码:

<?php
require('myfile.php');

    //here is the user_id, which is the corresponding user_id for username +5555555

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

//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,
        'private_review_ids' => $results[$catId],
        ];
}, array_keys($results));
echo json_encode($jsonData);


    //**********************

//select all rows where public_or_private column = 2
//in review table
$sql2 = "SELECT * FROM review WHERE public_or_private = 2";
$result2 = mysqli_query($con,$sql2);

    //fetch all associated rows where public_or_private column = 2
    while ($row = $result2->fetch_assoc()) {

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

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

    //make an array called $results
    $results2[$row['cat_id']][] = $review2_id;              

    }

    $jsonData2 = array_map(function($cat2Id) use ($results2) {
    return [
        'category' => $cat2Id,
        'public_review_ids' => $results2[$cat2Id],
        ];
}, array_keys($results2));
echo json_encode($jsonData2);


?>

【问题讨论】:

标签: php json


【解决方案1】:

如果重构代码,您可以立即将查询结果附加到所需的数据结构中,从而消除对数据进行 4 次迭代(每次两次)的需要。

如果您执行公开和私人评论查询,使其结果位于变量 $publicReviews$privateReviews 中,则:

<?php

// Public and private review query results
$publicReviews = $stmt1->get_result();
$privateReviews = $stmt2->get_result();

// Prepare combined reviews array
$reviews = [];

// Iterate through private review results and append to combined reviews
while (($row = $privateReviews->fetch_assoc())) {
    $category_id = $row['cat_id'];
    $review_id = $row['review_id'];

    $reviews[$category_id]['category'] = $category_id;
    $reviews[$category_id]['private_review_ids'][] = $review_id;
    $reviews[$category_id]['public_review_ids'] = [];
}

// Iterate through public review results and append to combined reviews
while (($row = $publicReviews->fetch_assoc())) {
    $category_id = $row['cat_id'];
    $review_id = $row['review_id'];

    $reviews[$category_id]['category'] = $category_id;

    // Create empty private reviews array, where it doesn't exist
    if (! isset($reviews[$category_id]['private_review_ids'])) {
        $reviews[$category_id]['private_review_ids'] = [];
    }

    // Add review id to public reviews where it doesn't exist in private reviews
    if (! in_array($review_id, $reviews[$category_id]['private_review_ids'])) {
        $reviews[$category_id]['public_review_ids'][] = $review_id;
    }
}

echo json_encode(array_values($reviews));

【讨论】:

  • 我得到Parse error: syntax error, unexpected '?' in /var/www/html/CategorySearch.php on line 43 这是$reviews[$cat_id]['public_review_ids'] = $reviews[$cat_id]['public_review_ids'] ?? []; 的行当我删除额外的? 我得到Parse error: syntax error, unexpected ';' in /var/www/html/CategorySearch.php on line 43
  • 你没有使用 PHP7+ 吗?
  • 看来我的 PHP 版本是 5.5.9-1ubuntu4.21。我应该更新吗?虽然不是那么旧,2017 年 2 月。无论如何,我在获取变量 $publicReviews 的结果时遇到问题,让我进一步研究一下......
  • PHP 5.5 于 2016 年 7 月停产,所以是的,您可能需要考虑升级。至于变量$publicReviews,为了清楚起见,我只是在答案中重命名了它们。您只需要以正确的顺序获取查询结果,while 循环就可以工作。我将更新我的答案,使其在没有 null coalese 运算符的情况下工作。
  • Tx,JSON 应该是一个数组吧?现在的输出是这样的:{"383":{"private_review_ids":[353],"public_review_ids":[]},"203":{"private_review_ids":[149],"public_review_ids":[]},"239":{"private_review_ids":[201],"public_review_ids":[]}} 我希望它是这样的:[{"category":"383", "private_review_ids":[353],"public_review_ids":[]},"category":"203","private_review_ids":[149],"public_review_ids":[]},"category":"239","private_review_ids":[201],"public_review_ids":[]}]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-17
  • 2019-02-01
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
相关资源
最近更新 更多