Untitled

mail@pastecode.io avatar
unknown
php
2 months ago
2.1 kB
7
Indexable
Never
<?php

$json1 = '[{"id": "0","rels": {"spouses": ["8c6cc5cd-9978-4c7e-98f0-67470c4d1d88"]},"data": {"name": "Marco","surname": "Zappa","birthday": 2004,"avatar": "","gender": "M"},"main": true,"hide_rels": false},{"id": "8c6cc5cd-9978-4c7e-98f0-67470c4d1d88","data":{"gender": "F","name": "Katia","surname":"Caliendo","birthday": ""},"rels": {"spouses": ["0"]},"main": false}]';

$json2 = '[{"id":"0","rels":{"mother":"ce7c4b34-100b-4c45-bb0a-109309e2158d","father":"0e498700-5849-450a-866a-e52bfec129e7"},"data":{"name":"Marco","surname":"Zappa","birthday":"24-05-2004","avatar":"","gender":"M"},"main":true,"hide_rels":false},{"id":"ce7c4b34-100b-4c45-bb0a-109309e2158d","data":{"gender":"F","name":"Anna Maria","surname":"Mosti","birthday":"1976-10-18"},"rels":{"children":["0"],"spouses":["0e498700-5849-450a-866a-e52bfec129e7"]},"main":false,"hide_rels":false},{"id":"0e498700-5849-450a-866a-e52bfec129e7","data":{"gender":"M","name":"Agostino","surname":"Zappa","birthday":"1972-11-20"},"rels":{"spouses":["ce7c4b34-100b-4c45-bb0a-109309e2158d"],"children":["0"]},"main":false,"hide_rels":false}]';


$data1 = json_decode($json1, true);
$data2 = json_decode($json2, true);

$main_true_item_1 = null;
$main_true_item_2 = null;

foreach ($data1 as $item) {
    if ($item['main']) {
        $main_true_item_1 = $item;
        break;
    }
}

foreach ($data2 as $item) {
    if ($item['main']) {
        $main_true_item_2 = $item;
        break;
    }
}

$result = array_merge($data1, $data2);

if ($main_true_item_1 !== null && $main_true_item_2 !== null) {
    $index = array_search($main_true_item_2, $result);
    unset($result[$index]);
}

foreach ($result as &$item) {
    if ($item['id'] === $main_true_item_1['id']) {
        $item['rels'] = $main_true_item_1['rels'];
        $item['rels']['spouses'] = $main_true_item_2['rels']['spouses'];
    }
    if ($item['id'] === $main_true_item_2['id']) {
        $item['rels'] = $main_true_item_2['rels'];
        $item['rels']['spouses'] = $main_true_item_1['rels']['spouses'];
    }
}

$result_json = json_encode(array_values($result), JSON_PRETTY_PRINT);

echo $result_json;

Leave a Comment