【问题标题】:php merge json arraysphp合并json数组
【发布时间】:2017-02-24 13:34:05
【问题描述】:

数组 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) 以及各种我可以通过谷歌在我的头脑和其他地方想到的东西。我正在寻找一种将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"}
]

PlayerID 始终是唯一的。希望听到我可以做些什么来合并这两个数组(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操作
  • 我尝试了 mySQL JOIN,但无法解决这些问题,因为它来自 2 个不同的表,但一个查询需要 GROUP BY 而其他查询不需要。
  • 在上面编辑以包含 mySQL
  • 在第二个查询中,您可以尝试使用 nCity.PlayerID、nPlayer.userName、nPlayer.castleCount、.....
  • @sgkdnay。我已经提供了有关您所需输出的解释,也提供了代码。分享想法,如果您遇到任何障碍,请告诉我。

标签: php mysql arrays json


【解决方案1】:

详细说明

您可以根据获得的键值加入 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 ) )

之后,我们必须根据key获得merge the two arrays,即unique

因此代码的功能如下。

我已将 PlayerID 视为 UNIQUE 参数,并合并了数组。

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() 获得的 array() 并执行操作。

注意:它把unique ID作为生成的每一行的array key

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_strings,然后您必须通过 foreach() 将它们都 llop,然后与您需要加入的 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"}]

【讨论】:

  • 这种方法效果很好。直到有人提到加入,我只是把头撞到桌子上,并没有意识到它的简化。对于我计划使用其他 JSON 进行的额外工作,肯定会很有用
【解决方案2】:

假设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);

这是live demo

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      你能用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"
                   }
      }
      

      【讨论】:

        【解决方案5】:
        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,
          ),
        )
        
        

        【讨论】:

          【解决方案6】:

          这个 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 数据的引号。对不起,我的错,已更正

          【讨论】:

          • 这也解决不了他的问题。请好好参考问题。他需要根据键合并数组。此解决方案将仅合并数组。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-25
          • 2020-02-29
          • 1970-01-01
          • 1970-01-01
          • 2023-03-16
          相关资源
          最近更新 更多