我有两个数字数组(这些数组总是具有相同数量的键和值)。
$array1 = array(0 => "key1", 1 => "key2");
$array2 = array(0 => "value1", 1 => "value2");
$array_final = array(value of the $array1 => $value of the array2);
如果我写了一段时间并填写$array_final
,它只会填写最后一个键和值
所以就像:
for ($i = 0; $i < count($array(1))
{
$array_final = array($array1[$i] => $array2[$i]);
}
$array_final = array("key2" => "value2");
但我想:
$array_final = array("key1" => "value1", "key2" => "value2");
答案 0 :(得分:1)
它完全符合您的需要
所以基本上
$array1 = array(0 => "key1", 1 => "key2");
$array2 = array(0 => "value1", 1 => "value2");
$array_final = array_combine($array1, $array2);
答案 1 :(得分:1)
for ($i=0; $i< sizeof($array1) && $i< sizeof($array2) ; $i++)
{
$array_final[$array1[$i]] =$array2[$i];
}
答案 2 :(得分:0)
您可以尝试以下代码。
$array1 = array(0 => "key1", 1 => "key2"); $array2 = array(0 => "value1", 1 => "value2"); $array_final = combine_if_same_keys($array1,$array2); print_r($array_final); function combine_if_same_keys( $array_one, $array_two ) { $expected = false; ksort($array_one); ksort($array_two); $diff = array_diff_key($array_one, $array_two); if( empty($diff) && count($array_one) == count($array_two) ) { $expected = array_combine( $array_one, $array_two ); } return $expected; }