从其他2个数组创建一个数组

时间:2011-07-28 09:30:51

标签: php

$arrayA = Array ( 
                 [0] => 1, 
                 [1] => 2, 
                 [2] => 4 
                )

$arrayB = Array ( 
                 [1] => Dog, 
                 [2] => Cat, 
                 [3] => Cow, 
                 [4] => Duck 
                )

如何创建一个$arrayC来获取上述2个数组的值:

$arrayC = Array ( 
                 [1] => Dog, 
                 [2] => Cat, 
                 [4] => Duck 
                )

理论上,它是这样的:

$arrayC = Array ( 
                 [$arrayA[0]] => $arrayB[$arrayA[0]],
                 [$arrayA[1]] => $arrayB[$arrayA[1]],
                 [$arrayA[2]] => $arrayB[$arrayA[2]]
                )

感谢。

5 个答案:

答案 0 :(得分:7)

您可以在没有foreach(Demo)的情况下以优雅的方式执行此操作:

$arrayC = array_intersect_key($arrayB, array_flip($arrayA));

请参阅array_intersect_key[Docs]array_flip[Docs]

答案 1 :(得分:2)

$arrayC = array();
foreach ($arrayA as $key) {
  if (isset($arrayB[$key])) {
     $arrayC[$key] = $arrayB[$key];
  }
}

答案 2 :(得分:1)

无需自己编写foreach循环:

//get only the keys that are in both
$arrayA = array_intersect_key(array_fill_keys($arrayA , true), $arrayB);
$arrayB = array_intersect_key($arrayB, $arrayA);

//combine the arrays
$arrayC = array_combine(array_keys($arrayA), $arrayB);

答案 3 :(得分:1)

foreach($arrayA as $i => $key) {
    $arrayC[$key] = $arrayB[$arrayA[$i]];
}

$arrayC将是:

Array ( [1] => Dog [2] => Cat [4] => Duck ) 

答案 4 :(得分:0)

您可以尝试这样做: -

foreach ($arrayA as $number)
{
  if(isset($arrayB[$number])
  {
    $arrayC[$number] = $arrayB[$number];
  }
}