PHP合并JSON数组

3

数组 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"}
]

数组 2:

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

这两个数组是通过fetch_assoc_all()从mySQL数据库中提取出来的。

我尝试了merge_array、merge_array_recursive、json_decode(xx,true)以及我能想到的所有东西,包括在Google上搜索。我正在寻找一种将array1和array2合并成类似以下内容的方法:

[
{"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"}
]

玩家ID始终是唯一的。希望听到我能够合并这两个数组(array1,array2)的见解。

(附加/编辑) 对于那些想知道MySQL是什么样子的人(我无法理解JOIN语句):

$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';

当你提取数据时,最好在查询中使用MYSQL JOIN操作。 - user3419778
我尝试在mySQL中使用JOIN,但由于来自两个不同的表,其中一个查询需要GROUP BY而另一个则不需要,因此我无法理解它们。 - sgkdnay
编辑上面的内容以包括mySQL - sgkdnay
在第二个查询中,您可以尝试使用nCity.PlayerID、nPlayer.userName、nPlayer.castleCount等。 - user3419778
@sgkdnay。我已经提供了关于所需输出的解释,并提供了代码。分享想法,让我知道是否遇到任何障碍。 - Naresh Kumar P
6个回答

4

详细解释

假设您已经获取了一个关键值,您可以根据该关键值加入JSON数组,只需在json_array()下面提供您要加入的键即可。
我将根据PHP代码考虑以下json_objects
<?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"}
]';
?>

因此,为了合并json_objects,我们必须首先对我们获取的两个数组使用json_decode()
$decode_one = json_decode($array1,TRUE);
$decode_two = json_decode($array2,TRUE);

因此,json_decoded() 字符串的输出如下所示。
第一个解码字符串:
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 ) ) 

第二个解码字符串:

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

之后,我们需要基于对我们而言是唯一的“键”合并两个数组。因此,这段代码的函数如下所示。我已将PlayerID视为唯一参数并将数组合并。
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;
  }

您需要在需要执行 array_merge() 操作的代码中像这样调用函数。
$merged_array = merge_json_decoded_arrays($decode_one,$decode_two);

最终,完整的代码如下所示(包括设置)。

完整代码:

<?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);
?>

为了查看合并后的数组,您需要使用print_r()函数打印数组并查看。 数组输出代码:
print_r($merged_array);

输出:

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 ) )

如果您需要JSON输出,您需要对获得的数组进行json_encode()操作。

注意: 它将每一行的唯一ID作为数组键

JSON输出代码:

print_r(json_ecode($merged_array));

输出:

{"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"}}

最快的执行方法是采用以下方式

您需要解码json字符串,然后通过foreach()循环遍历它们,然后与需要连接的array()组合。

$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.

输出:

[{"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"}]

这个方法很有效。直到有人提到JOIN,我才恍然大悟它的简化之处。对于我计划在其他JSON上进行的额外工作肯定会非常有用。 - sgkdnay

0

假设json1json2是您的两个JSON字符串,合并这两个JSON字符串的解决方案如下:

  • 首先使用json_decode()函数解码这两个JSON字符串,以获取$decodedArray1$decodedArray2数组。
  • 运行两个嵌套的foreach循环将$decodedArray2合并到$decodedArray1数组中。
  • 最后,在$decodedArray1数组上应用json_encode()函数以获取结果JSON字符串。

以下是代码:

$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);

这里是实时演示

0

PHP中没有可以实现您想要功能的函数。如果您查看常见的框架,您会发现它们使用类似以下合并功能:

/**
 * @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;
}

通过上述方法,您可以对每个元素进行json_decode(),然后合并它们,最后将结果json_encode()

为了完整起见,这里是上述合并函数的一个测试用例:

<?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,
                ),
            ),
        );
    }
}

0

请尝试使用foreach循环,好吗?

示例jSON数据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"}
]';

示例 jSON 数据 2:

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

首先,解码您获取的JSON数据以将其转换为数组

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

一旦转换,使用以下foreach循环来检查两个数组中的“PlayerID”是否相等。如果相同,则将其与结果数组合并,如下所示:

    $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;

      }
    }
  }

输出将会按照所需精确地合并以下数组:

             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"
             }
}

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,
  ),
)


-1

这段 PHP 代码应该可以解决问题:

$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);

编辑

忘记在 JSON 数据周围加上引号了。抱歉,是我的失误,已经更正。


这也不能解决他的问题。请仔细参考问题。他需要根据键合并数组。这个解决方案只会合并数组。 - Naresh Kumar P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接