0

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"
        }]
    }
}
';

1 Answer 1

1

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
)
Sign up to request clarification or add additional context in comments.

3 Comments

I make my answer from the json string, Did the loop needed for some validation checking?
If you can explain some about the loop than i can hep you better ways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.