Skip to content
Advertisement

Merge two JSON arrays and then sort them

How would I merge both JSON arrays and then sort the value of ID so that the result displays the highest number to the lowest number?

For example, my desired output from the script below would be:

  • 1 – Jimbo
  • 2 – Bob
  • 6 – Luke
  • 12 – Chris
  • 16 – Jonas
  • 36 – Sam

Here’s my JSON arrays:

$json1 ='
{
    "error": "trueee",
    "info": {
        "collections": [{
            "ID": "1"
            "Name": "Jimbo"
        }, {
            "ID": "36"
            "Name": "Sam"
        }, {
            "ID": "2",
            "Name": "Bob"
        }]
    }
}
';

$json2 ='
{
    "error": "trueee",
    "info": {
        "collections": [{
            "ID": "12"
            "Name": "Chris"
        }, {
            "ID": "6"
            "Name": "Luke"
        }, {
            "ID": "16"
            "Name": "Jonas"
        }]
    }
}
';

Advertisement

Answer

You need to merge the arrays from the json string. First json decode for getting the arr with associative array than get the columns of ID using array_column, after that you need to merge the two array and finally sort them.

Online Check and a Long Conversation

$json1 ='
{
    "error": "trueee",
    "info": {
        "collections": [{
            "ID": "1"
        }, {
            "ID": "36"
        }, {
            "ID": "2"
        }]
    }
}
';

$json2 ='
{
    "error": "trueee",
    "info": {
        "collections": [{
            "ID": "12"
        }, {
            "ID": "6"
        }, {
            "ID": "16"
        }]
    }
}
';

$arr1 = json_decode($json1, true);
$arr2 = json_decode($json2, true);

$arr1 = array_column($arr1['info']['collections'], "ID");
$arr2 = array_column($arr2['info']['collections'], "ID");

$arr = array_merge($arr1, $arr2);
sort($arr);
echo '<pre>';
print_r($arr);

Result:

Array
(
    [0] => 1
    [1] => 2
    [2] => 6
    [3] => 12
    [4] => 16
    [5] => 36
)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement