Вот что вы хотите:
<?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
Это дает мне это: Код + результат
Это все из-за того, что вы делаете 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"}]