[英]What is the easiest way to extract array's values from another array's keys
I have two arrays:我有两个 arrays:
$array1 = [1,2,3,4,5,6,7,8,9];
$array2 = [0,1,2,3];
I want to assign the values from the first array to another array according to the values from the second array as keys.我想根据第二个数组中的值作为键将第一个数组中的值分配给另一个数组。 So instead of doing it one by one like this:
所以不要像这样一个一个地做:
$array3 = [$array1[$array2[0]],$array1[$array2[1]],$array1[$array2[2]],$array1[$array2[3]]];
I tried to do it like this:我试着这样做:
$array3 = [$array1[$array2]];
But I got the following error:但我收到以下错误:
Warning: Illegal offset type
What I want to get is:我想要得到的是:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Any ideas what is the right way to do it?任何想法什么是正确的方法?
There are probably numerous ways to solve this.可能有很多方法可以解决这个问题。 Probably the simplest is to loop over the second array and add the corresponding values from the first into the new array...
可能最简单的是遍历第二个数组并将第一个数组中的相应值添加到新数组中......
$array3 = [];
foreach ( $array2 as $extract ) {
$array3[] = $array1 [ $extract ];
}
print_r($array3);
I found a short way:我找到了一个捷径:
array_map(function($x) use ($array1) { return $array1[$x]; }, $array2);
A simple foreach loop should do the trick.一个简单的 foreach 循环应该可以解决问题。 Loop over second array and check if its key is set in the first array.
遍历第二个数组并检查其键是否设置在第一个数组中。 If so, add to result, else skip.
如果是这样,添加到结果,否则跳过。
$array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$array2 = [0, 1, 2, 3];
$result = [];
foreach ($array2 as $value) {
if (isset($array1[$value])) {
$result[] = $array1[$value];
}
}
print_r($result);
From PHP7.4 you can use arrow function syntax and avoid the use()
declaration.从 PHP7.4 开始,您可以使用箭头 function 语法并避免
use()
声明。 If you don't want to call any custom functions and don't want a classic loop, you can make 3 native function calls to generate an indexed array of results.如果您不想调用任何自定义函数并且不想使用经典循环,则可以进行 3 次本机 function 调用以生成结果的索引数组。
$array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$array2 = [3, 4];
var_export(
array_values(array_intersect_key($array1, array_flip($array2)))
);
// array ( 0 => 4, 1 => 5, )
var_export(
array_map(fn($v) => $array1[$v], $array2)
);
// array ( 0 => 4, 1 => 5, )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.