简体   繁体   中英

php merge json arrays

array 1:

[
{"PlayerID":"17794204","userName":"Vandiel","castleCount":"9","NotUpd":"1476253231000"},
{"PlayerID":"21532584","userName":"Mayland","castleCount":"1","NotUpd":"0"},
{"PlayerID":"21539896","userName":"Dana","castleCount":"9","NotUpd":"0"}
]

array 2:

[
{"PlayerID":"17794204","Trouble":"2"},
{"PlayerID":"21532584","Trouble":"0"},
{"PlayerID":"21539896","Trouble":"0"}
]

Those both were pulled from mySQL database using fetch_assoc_all()

I tried merge_array, merge_array_recursive, json_decode(xx,true) and all kinds of things I could think on top of my head and elsewhere via google. I'm looking for a way to merge both array1, array2 into something like:

[
{"PlayerID":"17794204","userName":"Vandiel","castleCount":"9","NotUpd":"1476253231000","Trouble":"2"},
{"PlayerID":"21532584","userName":"Mayland","castleCount":"1","NotUpd":"0","Trouble":"0"},
{"PlayerID":"21539896","userName":"Dana","castleCount":"9","NotUpd":"0","Trouble":"0"}
]

PlayerID are always unique. Hope to hear what insight I could do to merge those 2 arrays (array1,array2)

(Additonal/Edit) For those wondering what's mySQL looks like (I couldn't wrap my head around on JOIN statement):

$mSQL = 'SELECT nPlayer.PlayerID,userName,castleCount,IF(LastUpdate < (UNIX_TIMESTAMP() - 3720),LastUpdate*1000,0) NotUpd';
$mSQL .= ' FROM nPlayer';
$mSQL .= ' LEFT JOIN nMains ON nMains.mID = nPlayer.mID';
$mSQL .= ' WHERE nMains.Main = "'.$M.'"  AND nMains.Pass = "'.md5($P).'" AND nMains.Server = "'.$S.'"';
$mSQL .= ' ORDER BY nPlayer.PlayerID';

$mSQL = 'SELECT nCity.PlayerID,SUM(IF(Wartown > 0,1,0))+SUM(IF(support < 100,1,0))) Trouble';
$mSQL .= ' FROM nCity';
$mSQL .= ' INNER JOIN nPlayer ON nPlayer.PlayerID = nCity.PlayerID AND nPlayer.mID = nCity.mID';
$mSQL .= ' INNER JOIN nMains ON nMains.mID = nPlayer.mID';
$mSQL .= ' WHERE nMains.Main = "'.$M.'"  AND nMains.Pass = "'.md5($P).'" AND nMains.Server = "'.$S.'"';
$mSQL .= ' GROUP BY nCity.PlayerID';

Detailed Explanation

You can join the JSON array based on the key value that you obtain provided you have to give under which key you have to join the json_array() .

I am going to consider the json_objects as follows based on the PHP code.

 <?php $array1 = '[ {"PlayerID":"17794204","userName":"Vandiel","castleCount":"9","NotUpd":"1476253231000"}, {"PlayerID":"21532584","userName":"Mayland","castleCount":"1","NotUpd":"0"}, {"PlayerID":"21539896","userName":"Dana","castleCount":"9","NotUpd":"0"} ]'; $array2 = '[ {"PlayerID":"17794204","Trouble":"2"}, {"PlayerID":"21532584","Trouble":"0"}, {"PlayerID":"21539896","Trouble":"0"} ]'; ?>

Hence inorder to merget the json_objects we have to first use json_decode() for the both the arrays that we have obtained.

 $decode_one = json_decode($array1,TRUE); $decode_two = json_decode($array2,TRUE);

Hence the output for the json_decoded() string will be as follows.

First Decoded String:

 Array ( [0] => Array ( [PlayerID] => 17794204 [userName] => Vandiel [castleCount] => 9 [NotUpd] => 1476253231000 ) [1] => Array ( [PlayerID] => 21532584 [userName] => Mayland [castleCount] => 1 [NotUpd] => 0 ) [2] => Array ( [PlayerID] => 21539896 [userName] => Dana [castleCount] => 9 [NotUpd] => 0 ) )

Second Decoded String:

 Array ( [0] => Array ( [PlayerID] => 17794204 [Trouble] => 2 ) [1] => Array ( [PlayerID] => 21532584 [Trouble] => 0 ) [2] => Array ( [PlayerID] => 21539896 [Trouble] => 0 ) )

After that we have to merge the two arrays that we have obtained based on the key that is unique for us.

Hence the function for the code is as follows.

I have considered the PlayerID as the UNIQUE Parameter and has combined the array.

 function merge_json_decoded_arrays($decode_one,$decode_two) { $data = array(); $arrayAB = array_merge($decode_one,$decode_two); foreach ($arrayAB as $value) { $id = $value['PlayerID']; if (!isset($data[$id])) { $data[$id] = array(); } $data[$id] = array_merge($data[$id],$value); } return $data; }

You need to call the function like this from the code where you need to perform the array_merge() operations.

 $merged_array = merge_json_decoded_arrays($decode_one,$decode_two);

Finally the full code appears like this with the setup.

Full Code:

 <?php $array1 = '[ {"PlayerID":"17794204","userName":"Vandiel","castleCount":"9","NotUpd":"1476253231000"}, {"PlayerID":"21532584","userName":"Mayland","castleCount":"1","NotUpd":"0"}, {"PlayerID":"21539896","userName":"Dana","castleCount":"9","NotUpd":"0"} ]'; $array2 = '[ {"PlayerID":"17794204","Trouble":"2"}, {"PlayerID":"21532584","Trouble":"0"}, {"PlayerID":"21539896","Trouble":"0"} ]'; $decode_one = json_decode($array1,TRUE); $decode_two = json_decode($array2,TRUE); function merge_json_decoded_arrays($decode_one,$decode_two) { $data = array(); $arrayAB = array_merge($decode_one,$decode_two); foreach ($arrayAB as $value) { $id = $value['PlayerID']; if (!isset($data[$id])) { $data[$id] = array(); } $data[$id] = array_merge($data[$id],$value); } return $data; } $merged_array = merge_json_decoded_arrays($decode_one,$decode_two); ?>

In order to view the merged array you need to print_r() the array and view it.

Array Output Code:

 print_r($merged_array);

Output:

 Array ( [17794204] => Array ( [PlayerID] => 17794204 [userName] => Vandiel [castleCount] => 9 [NotUpd] => 1476253231000 [Trouble] => 2 ) [21532584] => Array ( [PlayerID] => 21532584 [userName] => Mayland [castleCount] => 1 [NotUpd] => 0 [Trouble] => 0 ) [21539896] => Array ( [PlayerID] => 21539896 [userName] => Dana [castleCount] => 9 [NotUpd] => 0 [Trouble] => 0 ) )

If you need it as the JSON output you have to json_encode() the obtained array() and perform the operations.

Note: It takes the unique ID as the array key for each row that is been generated.

JSON Output Code:

 print_r(json_ecode($merged_array));

Output:

 {"17794204":{"PlayerID":"17794204","userName":"Vandiel","castleCount":"9","NotUpd":"1476253231000","Trouble":"2"},"21532584":{"PlayerID":"21532584","userName":"Mayland","castleCount":"1","NotUpd":"0","Trouble":"0"},"21539896":{"PlayerID":"21539896","userName":"Dana","castleCount":"9","NotUpd":"0","Trouble":"0"}}

Fastest Execution Method will take up this way

You need to decode the json_strings and then you have to llop both of them through the foreach() and then combine with the array() that you need to join with it.

 $decode_one = json_decode($array1,TRUE); $decode_two = json_decode($array2,TRUE); foreach ($decode_one as $key => $first_value) { foreach ($decode_two as $key_two => $second_value) { if($first_value['PlayerID']==$second_value['PlayerID']) { $decode_one[$key]['Trouble'] = $second_value['Trouble'];//Here if the key exists it will join the Trouble with the First decoded array } else {} } } $combined_output = json_encode($decode_one); //This will return the output in json format.

Output:

 [{"PlayerID":"17794204","userName":"Vandiel","castleCount":"9","NotUpd":"1476253231000","Trouble":"2"},{"PlayerID":"21532584","userName":"Mayland","castleCount":"1","NotUpd":"0","Trouble":"0"},{"PlayerID":"21539896","userName":"Dana","castleCount":"9","NotUpd":"0","Trouble":"0"}]

Suppose json1 and json2 are your two JSON strings, the solution to merge these two JSON strings would be like this:

  • First decode these two JSON strings using json_decode() function to get $decodedArray1 and $decodedArray2 arrays.
  • Run two nested foreach loops to merge $decodedArray2 into $decodedArray1 array.
  • Finally, apply json_encode() function on $decodedArray1 array to get the resultant JSON string.

Here's the code:

$decodedArray1 = json_decode($json1, true);
$decodedArray2 = json_decode($json2, true);

foreach($decodedArray1 as $key => $array1){
    foreach($decodedArray2 as $array2){
        if($array1['PlayerID'] == $array2['PlayerID']){
            $decodedArray1[$key]['Trouble'] = $array2['Trouble'];
        }
    }
}

$resultantJson = json_encode($decodedArray1);

Here's the live demo

There is no function in PHP that does what you want. If you look around the usual suspect frameworks you'll find they use a merge functionality like the following:

/**
 * @param array $array
 * @param array $other
 *
 * @return array
 */
function _array_merge(array $array, array $other)
{
    foreach ($other as $key => $value) {
        if (isset($array[$key]) || array_key_exists($key, $array)) {
            if (is_int($key)) {
                $array[] = $value;
            } elseif (is_array($value) && is_array($array[$key])) {
                $array[$key] = _array_merge($array[$key], $value);
            } else {
                $array[$key] = $value;
            }
        } else {
            $array[$key] = $value;
        }
    }

    return $array;
}

With the above you can json_decode() each element then merge them and then json_encode() the result.

For completeness, here is a test case for the above merge function:

<?php

class ArrayMergeTest extends \PHPUnit_Framework_TestCase
{
    public function testMerge(array $expected, array $a, array $b)
    {
        $this->assertSame($expected, _array_merge($a, $b));
    }

    /**
     * @return array
     */
    public function provideMerge()
    {
        return array(
            'should-preserve-integer-keys' => array(
                array(
                    2 => array('a', 'b', 'c'),
                    3 => array('d', 'e', 'f'),
                ),
                array(2 => array('a', 'b', 'c')),
                array(2 => array('d', 'e', 'f')),
            ),
            'should-merge-when-no-existing-key' => array(
                array(
                    'a' => array('b', 'c'),
                    'd' => array('e', 'f'),
                ),
                array('a' => array('b', 'c')),
                array('d' => array('e', 'f')),
            ),
            'should-overwrite-key-when-not-array' => array(
                array('a' => 'b'),
                array('a' => 'foo'),
                array('a' => 'b'),
            ),
            'should-merge-recursive' => array(
                array('a' => array(0 => 'b', 1 => 'c')),
                array('a' => array('b')),
                array('a' => array('c')),
            ),
            'should-replace-string-keys' => array(
                array('foo' => 'baz', 'bar' => 'bat'),
                array('foo' => 'bar', 'bar' => array()),
                array('foo' => 'baz', 'bar' => 'bat'),
            ),
            'should-merge-nested' => array(
                array('a' => array('b' => array('baz', 'bat'))),
                array('a' => array('b' => array('baz'))),
                array('a' => array('b' => array('bat'))),
            ),
            'should-merge-simple-keys' => array(
                array('a' => 'a_val', 'b' => 'b_val'),
                array('a' => 'a_val'),
                array('b' => 'b_val'),
            ),

            // Ensure documentation examples work

            'doc_example_1' => array(
                array(42 => 'x', 43 => 'y'),
                array(42 => 'x'),
                array(42 => 'y'),
            ),

            'doc_example_2_a' => array(
                array('x' => 'b'),
                array('x' => 'a'),
                array('x' => 'b'),
            ),
            'doc_example_2_b' => array(
                array('x' => 'b'),
                array('x' => array('a')),
                array('x' => 'b'),
            ),
            'doc_example_2_c' => array(
                array('x' => array('b')),
                array('x' => 'a'),
                array('x' => array('b')),
            ),
            'doc_example_2_d' => array(
                array('x' => array('a', 'b')),
                array('x' => array('a')),
                array('x' => array('b')),
            ),
            'merge-integer-and-string-keys' => array(
                array(
                    0 => 'foo',
                    3 => 'bar',
                    'baz' => 'baz',
                    4 => array(
                        'a',
                        1 => 'b',
                        'c',
                    ),
                    5 => 'baz',
                    6 => array(
                        'd' => 'd',
                    ),
                ),
                array(
                    'foo',
                    3 => 'bar',
                    'baz' => 'baz',
                    4 => array(
                        'a',
                        1 => 'b',
                        'c',
                    ),
                ),
                array(
                    'baz',
                    4 => array(
                        'd' => 'd',
                    ),
                ),
            ),
            'merge-arrays-recursively' => array(
                array(
                    'foo' => array(
                        0 => 'baz',
                        1 => 'baz',
                    ),
                ),
                array(
                    'foo' => array(
                        'baz',
                    ),
                ),
                array(
                    'foo' => array(
                        'baz',
                    ),
                ),
            ),
            'replace-string-keys' => array(
                array(
                    'foo' => 'baz',
                    'bar' => 'bat',
                ),
                array(
                    'foo' => 'bar',
                    'bar' => array(),
                ),
                array(
                    'foo' => 'baz',
                    'bar' => 'bat',
                ),
            ),
            'merge-with-null' => array(
                array(
                    'foo' => 'baz',
                    null => 'zad',
                    'cat' => 'bar',
                    'god' => null,
                ),
                array(
                    'foo' => null,
                    null => 'rod',
                    'cat' => 'bar',
                    'god' => 'rad',
                ),
                array(
                    'foo' => 'baz',
                    null => 'zad',
                    'god' => null,
                ),
            ),
        );
    }
}

Could you please try it using foreach loop?

Example jSON data 1:

  $json1='[
  {"PlayerID":"17794204","userName":"Vandiel","castleCount":"9","NotUpd":"1476253231000"},
{"PlayerID":"21532584","userName":"Mayland","castleCount":"1","NotUpd":"0"},
{"PlayerID":"21539896","userName":"Dana","castleCount":"9","NotUpd":"0"}
]';

Example jSON data 2:

$json2='[
 {"PlayerID":"17794204","Trouble":"2"},
 {"PlayerID":"21532584","Trouble":"0"},
 {"PlayerID":"21539896","Trouble":"0"}
]';

At first decode your fetched json data in order to convert as arrays

$array1=json_decode($json1,true);
$array2=json_decode($json2,true);

Once converted use following foreach loop in order to check 'PlayerID' is equal in both arrays. If same then merge with result array as following scripts:

    $result = array();

    foreach($array1 as $data1)
    {
      foreach($array2 as $data2)
      {
      if($data1['PlayerID'] == $data2['PlayerID'])
      {
        $tmp = array("Trouble" => $data2['Trouble']);
        $tmp = array_merge($data1, $tmp);
        $result[] = $tmp;

      }
    }
  }

Output would be merged following array exactly as wanted :

             array(3) {
             [0]=>
               array(5) {
               ["PlayerID"]=>
               string(8) "17794204"
               ["userName"]=>
                string(7) "Vandiel"
                ["castleCount"]=>
                string(1) "9"
                ["NotUpd"]=>
                 string(13) "1476253231000"
                ["Trouble"]=>
                string(1) "2"
                }
              [1]=>
                 array(5) {
                ["PlayerID"]=>
                string(8) "21532584"
                ["userName"]=>
                 string(7) "Mayland"
                 ["castleCount"]=>
                 string(1) "1"
                 ["NotUpd"]=>
                  string(1) "0"
                 ["Trouble"]=>
                  string(1) "0"
                 }
             [2]=>
               array(5) {
               ["PlayerID"]=>
               string(8) "21539896"
              ["userName"]=>
              string(4) "Dana"
              ["castleCount"]=>
              string(1) "9"
              ["NotUpd"]=>
              string(1) "0"
              ["Trouble"]=>
              string(1) "0"
             }
}
function mergeArrays(array $arr1, array $arr2, string $idKeyName) {
        $data = [];
        foreach ($arr1 as $value) {
            $id = $value[$idKeyName];
            $data[$id] = $value;
        }

        foreach ($arr2 as $value) {
            $id = $value[$idKeyName];
            if (isset($data[$id])) {
                $data[$id] = array_merge($data[$id], $value);
            } else {
                $data[$id] = $value;
            }
        }

        return array_values($data);
    }
$arr1 = [["id" => "66395", "substanceId" => 182], ["id" => "66396", "substanceId" => 183]];
$arr2 = [["id" => "66395_new", "substanceId" => 182], ["id" => "66397", "substanceId" => 184]];
$result = mergeArrays($arr1, $arr2, 'substanceId');

# var_export($result)
array (
  0 => 
  array (
    'id' => '66395_new',
    'substanceId' => 182,
  ),
  1 => 
  array (
    'id' => '66396',
    'substanceId' => 183,
  ),
  2 => 
  array (
    'id' => '66397',
    'substanceId' => 184,
  ),
)

This PHP code should do the trick:

$array1 = json_decode('[
    {"PlayerID":"17794204","userName":"Vandiel","castleCount":"9","NotUpd":"1476253231000"},
    {"PlayerID":"21532584","userName":"Mayland","castleCount":"1","NotUpd":"0"},
    {"PlayerID":"21539896","userName":"Dana","castleCount":"9","NotUpd":"0"}
]');
$array2 = json_decode('[
    {"PlayerID":"17794204","Trouble":"2"},
    {"PlayerID":"21532584","Trouble":"0"},
    {"PlayerID":"21539896","Trouble":"0"}
]');
$arrays_merged = array_merge($array1, $array2);

EDIT

Forgot quotes around json data. Sorry, my bad, has been corrected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM