在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中文網其他相關文章!