开发者

Create an array from 2 other arrays

$arrayA = Array ( 
                 [0] => 1, 
                 [1] => 2, 
                 [2] => 4 
开发者_如何学C                )

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

How do I create an $arrayC that takes the value from the above 2 arrays:

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

Theoretically, it's something like this:

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

Thanks.


You can do this in elegant way without foreach (Demo):

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

See array_intersect_key[Docs] and array_flip[Docs]


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


No need to write the foreach loop yourself:

//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);


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

$arrayC will be:

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


You can try to do something like this :-

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜