我想要合并这些数组:
$arr1 = array(1 => "a", 2 => "b", 3 => "c", 4 => "d");
$arr2 = array(1 => 5, 3 => 7, 4 => 9);
我想要这个:
$arr3 = array("a" => 5, "c" => 7, d => 9);
我想忽略关键索引" 2"在$ arr1上,因为它在$ arr2上不存在。
因此,我想仅在密钥索引匹配时才进行组合,仅将值与相同的原始密钥组合。
答案 0 :(得分:1)
你走了。
<?php
$arr1 = array(1 => "a", 2 => "b", 3 => "c", 4 => "d");
$arr2 = array(1 => 5, 3 => 7, 4 => 9);
$arr3 = array();
foreach ($arr1 as $key => $value) {
if(isset($arr2[$key])){
$arr3[$value] = $arr2[$key];
}
}
print_r($arr3);
?>
答案 1 :(得分:1)
试试这个:
$arr1 = array(1 => "a", 2 => "b", 3 => "c", 4 => "d");
$arr2 = array(1 => 5, 3 => 7, 4 => 9);
$result = array_combine(array_intersect_key($arr1, $arr2), $arr2);
产生:
Array
(
[a] => 5
[c] => 7
[d] => 9
)
答案 2 :(得分:0)
你会做这样的事情,它没有经过测试,但我认为它会起作用。 @Adrian所说的看起来更好。我没有使用foreach($ array作为$ key =&gt; $ val)。那更好。
//first merge all arrays into one (if you want)
$data = array_merge($arr1, $arr2);
$bucket = array();
$ignored = array('2', '3', '4') //array indexes to ignore
foreach($data as $item)
{
if(in_array($item[$ignored]))
{
continue;
}
else
{
array_merge($bucket, $item);
}
}
答案 3 :(得分:0)
试试这个..
使用“array_key_exists”
$arr1 = array(1 => "a", 2 => "b", 3 => "c", 4 => "d");
$arr2 = array(1 => 5, 3 => 7, 4 => 9);
foreach($arr1 as $key=>$value)
{
if (array_key_exists($key, $arr2)) {
$arr3[$value]=$arr2[$key];
}
}
print_r($arr3);
数组([a] =&gt; 5 [c] =&gt; 7 [d] =&gt; 9)
答案 4 :(得分:0)
您可以尝试这样的事情:
function combineArrays( $array1, $array2 ){
$array3 = array();
foreach ($array1 as $key => $value) {
if( isset($array2[$key]) ) { $array3[$value] = $array2[$key]; }
}
return $array3;
}
使用它像:
$arr3 = combineArrays($arr1, $arr2);
答案 5 :(得分:0)
使用array_key_exists的简单方法:
$ arr1 = array(1 =&gt;&#34; a&#34;,2 =&gt;&#34; b&#34;,3 =&gt;&#34; c&#34;,4 =&gt; ;&#34; d&#34;);
$ arr2 = array(1 =&gt; 5,3 =&gt; 7,4&gt; 9);
$new = array();
foreach ($arr2 as $key => $value) {
if(array_key_exists($key, $arr1)) {
$array[$arr1[$key]] = $arr2[$key];
}
}
print_r($array);
数组([a] =&gt; 5 [c] =&gt; 7 [d] =&gt; 9)