【问题标题】:Merge two JSON array in PHP在 PHP 中合并两个 JSON 数组
【发布时间】:2019-06-11 22:24:48
【问题描述】:

我需要在 PHP 中合并两个 json 文件 。一个起初是空的,另一个在每次调用时都会改变。

我发现很多代码可以在 PHP 中将两个 JSON 数组合并为一个,但它对我不起作用。

$final_array = array();
$first_json = file_get_contents("test3.json");
$second_json = file_get_contents("my-file.json");


if(json_decode($first_json,true) == null){
    $final_array[] = json_decode($second_json,true);
    $merge_final_array = json_encode(json_decode($second_json,true));
}else{
    $final_array[] = json_decode($first_json,true);
    $final_array[] = json_decode($second_json,true);
    $merge_final_array = json_encode($final_array);
}

file_put_contents("test3.json", $merge_final_array);
$merge_final_array = null;

我将在“my-file.json”中找到的数据递归地添加到“test3.json”文件中。

这应该给我:

[{"score":15,"win":true,"device":"Android SDK built for x86"},{"score":"Finish","device":"Android SDK built for x86","win":true},{"win":true,"score":"Finish","device":"Android SDK built for x86"},{"score":16,"scenario":"Finish","win":true,"device":"Android SDK built for x86"}]

因为它给了我:

[[[{"score":15,"win":true,"device":"Android SDK built for x86"},{"score":"Finish","device":"Android SDK built for x86","win":true}],{"win":true,"score":"Finish","device":"Android SDK built for x86"}],{"score":16,"scenario":"Finish","win":true,"device":"Android SDK built for x86"}]

我也试过json_encode(array_merge(json_decode($first_json, true),json_decode($second_json, true)))的方法 它给了我这个: Code + result

我做错了什么?

【问题讨论】:

标签: php json merge


【解决方案1】:

您首先需要将您的JSON 转换为数组,然后才能在PHP 中使用它。

首先,您需要在 PHP 中创建一个新的空数组,并将 JSON 数组添加到该空数组中。
然后将数组再次编码为JSON 并将其写入文件。
您的完整代码:

$first_json = file_get_contents("test3.json");
$second_json = file_get_contents("my-file.json");

$first_array = json_decode($first_json, true); // make array of json
$second_array = json_decode($second_json, true); // make array of json

$final_array = array(); // create an empty array 
$final_array[] = $first_array; // add first array to empty array
$final_array[] = $second_array;  // add second array to array

$final_json = json_encode($final_array); // make a json from the array again

file_put_contents("test3.json", $final_json); // put the json inside a new file 

【讨论】:

  • 第一个参数不是数组(代码在合并时给了我这个错误)
  • test-3 json 起初是空的,也许这就是原因?
  • 如果我打印 final_array 它只返回最后一个 JSON 元素而不合并:/
  • @JeremyBensoussan 那么您的 json 文件之一为空或 json 无效
  • 查看我在我编辑的帖子中放的图片,你就会明白合并的问题
【解决方案2】:

这是你想要的:

<?php

$finalArray = [];

// file_get_contents("test3.json");
$firstFileContent = '{"score":15,"win":true,"device":"Android SDK built for x86"}';

// file_get_contents("my-file.json")
$secondFileContent = '{"score":"Finish","device":"Android SDK built for x86","win":true}';

$firstJson = json_decode($firstFileContent, true);
if(JSON_ERROR_NONE === json_last_error()){
    $finalArray[] = $firstJson;
}

$finalArray[] = json_decode($secondFileContent, true);

$finalJson = json_encode($finalArray);

http://sandbox.onlinephpfunctions.com/code/404972fb59b4f7323f81ee444a1cb14f772f7748

它给了我这个:Code + result

这完全是因为您对两个数组执行了array_merge,而第二个数组将重写第一个值。您应该将第二个数组添加到结果数组中,而不是合并。

array_merge(["a" => 1], ["a" => 2]) // result: ["a" => 2]

$result[] = ["a" => 1];
$result[] = ["a" => 2];
// result: [["a" => 1], ["a" => 2]]

json_encode(array_merge(json_decode($first_json, true),json_decode($second_json, true)))

这是行不通的,因为在每个文件中你都编码了对象,而不是对象数组。如果您在第一个文件{"a":1} 和第二个文件{"a":2} 中有,当您合并它们的解码值时,结果将是{"a":2},但如果您将它们编辑为[{"a": 1}][{"a": 2}],则结果将是[{"a": 1}, {"a": 2}],因为现在您要合并转换为数组的对象数组,而不是对象。


如果你想递归地添加两个文件中的数据,你应该这样做:

<?php

$finalArray = [];

$firstFileContent = '[[{"score":15,"win":true,"device":"Android SDK built for x86"},{"score":"Finish","device":"Android SDK built for x86","win":true}],{"win":true,"score":"Finish","device":"Android SDK built for x86"}]';
$secondFileContent = '{"score":16,"scenario":"Finish","win":true,"device":"Android SDK built for x86"}';

mergeJsonRecursively($finalArray, $firstFileContent);
mergeJsonRecursively($finalArray, $secondFileContent);

function mergeJsonRecursively(array &$result, string $json)
{
    $decodedJson = json_decode($json);
    if (JSON_ERROR_NONE === json_last_error()) {
        tryToAddElementToResult($result, $decodedJson);

        if (is_array($decodedJson)) {
            foreach ($decodedJson as $element) {
                tryToAddElementToResult($result, $element);

                if (is_array($element)) {
                    mergeJsonRecursively($result, json_encode($element));
                }
            }
        }
    }
}

function tryToAddElementToResult(array &$result, $element)
{
    if (is_object($element)) {
        $result[] = json_decode(json_encode($element), true);
    }
}

$finalJson = json_encode($finalArray);

http://sandbox.onlinephpfunctions.com/code/f4858bcc87da34e4ee6639b2ee96c7ac3244ae1b

你会给出预期的结果:

[{"score":15,"win":true,"device":"Android SDK built for x86"},{"score":"Finish","device":"Android SDK built for x86","win":true},{"win":true,"score":"Finish","device":"Android SDK built for x86"},{"score":16,"scenario":"Finish","win":true,"device":"Android SDK built for x86"}]

【讨论】:

  • 这和我的回答一样,他说不行
【解决方案3】:

只需执行此操作即可。您可以添加自己的错误处理,但基本应该是这样的:

$final_array = array();
$first_json = file_get_contents("test3.json");
$second_json = file_get_contents("my-file.json");

$first_array = json_decode($first_json,true);
$second_array = json_decode($second_json,true);

if(is_array($first_array) and is_array(second_array)){
    $final_array = array_merge(first_array,second_array);
}
else if(!empty($first_array) and is_array($first_array)){
    $final_array = $first_array;
}
else if(!empty(second_array) and is_array(second_array)){
    $final_array = second_array;
}

$final_json = json_encode(final_array);

file_put_contents("test3.json", final_json);

【讨论】:

  • 第一个参数不是数组(代码在合并时给了我这个错误)
  • 编辑了我的帖子,很遗憾您的解决方案不起作用
  • 我添加了对数组的检查。立即尝试。
猜你喜欢
  • 1970-01-01
  • 2013-12-15
  • 2011-02-22
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多