比较数组以在PHP中生成键数组

时间:2022-03-05 21:33:25

I have a problem that I'm sure is easy to solve with PHP's inbuilt functions or with one or two lines of code, but I cant seem to find a solution using my limited experince.

我有一个问题,我确信使用PHP的内置函数或一行或两行代码很容易解决,但我似乎找不到使用我有限的经验的解决方案。

I have a master array:

我有一个主数组:

$master_array = ('location_1','location_2','location_3','location_4','location_5');

I get given an array:

我得到一个数组:

$submitted_array = ('location_1','location_3');

And I need to compare both arrays to form an array such as this:

我需要比较两个数组以形成如下数组:

$locations = (0,2);

Where the numbers in the $locations array are the locations of the $submitted_array elements in the $master_array.

$ locations数组中的数字是$ master_array中$ submitted_array元素的位置。

There must be a way of doing this without loops, surely.

肯定有一种没有循环的方法。

2 个解决方案

#1


3  

$result = array_keys(array_intersect($master_array , $submitted_array));
print_r($result);

#2


1  

$locations = array_keys(array_intersect($master_array, $submitted_array));

#1


3  

$result = array_keys(array_intersect($master_array , $submitted_array));
print_r($result);

#2


1  

$locations = array_keys(array_intersect($master_array, $submitted_array));