在 PHP 中合并具有匹配键的数组
问题陈述:
合并两个 PHP将具有匹配键的数组放入单个数组中,同时保留两个数组中的键值对。
示例数组:
数组 1:
<code class="php">array( [ "Camera1" => "192.168.101.71" ], [ "Camera2" => "192.168.101.72" ], [ "Camera3" => "192.168.101.74" ] )</code>
数组 2:
<code class="php">array( [ "Camera1" => "VT" ], [ "Camera2" => "UB" ], [ "Camera3" => "FX" ] )</code>
使用 array_map 的解决方案:
<code class="php">$array1 = array( ["Camera1" => "192.168.101.71"], ["Camera2" => "192.168.101.72"], ["Camera3" => "192.168.101.74"], ); $array2 = array( ["Camera1" => "VT"], ["Camera2" => "UB"], ["Camera3" => "FX"] ); $results = array(); array_map(function($a, $b) use (&$results) { $key = current(array_keys($a)); $a[$key] = array('ip' => $a[$key]); $key = current(array_keys($b)); $b[$key] = array('name' => $b[$key]); $results += array_merge_recursive($a, $b); }, $array1, $array2); var_dump($results);</code>
输出:
array (size=3) 'Camera1' => array (size=2) 'ip' => string '192.168.101.71' (length=14) 'name' => string 'VT' (length=2) 'Camera2' => array (size=2) 'ip' => string '192.168.101.72' (length=14) 'name' => string 'UB' (length=2) 'Camera3' => array (size=2) 'ip' => string '192.168.101.74' (length=14) 'name' => string 'FX' (length=2)
此解决方案保留两个数组中的键值对并将它们合并到一个数组中。 'array_merge_recursive' 函数用于递归合并数组,允许嵌套数组。
以上是如何将两个具有匹配键的 PHP 数组合并到一个数组中,同时保留两个数组中的键值对?的详细内容。更多信息请关注PHP中文网其他相关文章!