我有两个不同尺寸的数组,如下所示: 数组名为$ form_types;
Array
(
[0] => Array
(
[0] => 1
[form_type_id] => 1
[1] => Full name
[form_title] => Full name
[2] => text
[input_type] => text
)
[1] => Array
(
[0] => 2
[form_type_id] => 2
[1] => Birth date
[form_title] => Birth date
[2] => date
[input_type] => date
)
[2] => Array
(
[0] => 3
[form_type_id] => 3
[1] => Sex
[form_title] => Sex
[2] => text
[input_type] => text
)
[3] => Array
(
[0] => 4
[form_type_id] => 4
[1] => Address
[form_title] => Address
[2] => text
[input_type] => text
)
[4] => Array
(
[0] => 5
[form_type_id] => 5
[1] => City
[form_title] => City
[2] => select
[input_type] => select
)
名为$ _POST的数组(数组值1和5与$ form_types中的 form_type_id 相同):
Array
(
[1] => John Smith
[5] => Chicago
)
我需要找到交叉值的方法。在这种情况下,将是:
Array
(
[1] => text
[5] => select
)
我试过了:
$arr_input_types = array_intersect($input_types, $_POST);
但它返回零。
我也尝试过:
$arr_input_types = array_intersect(array_column($input_types, 'form_type_id'), array_keys($_POST));
但仅返回:
Array
(
[0] => 1
[4] => 5
)
答案 0 :(得分:1)
对于标准的php数组函数之一,您尝试做的事情有点过于复杂。但是,您可以通过一些循环轻松完成:
//populate arrays
$input_types[] = array (0 => 1, "form_type_id" => 1, 1 => "Full name", "form_title" => "Full name", 2 => "text" , "input_type" => "text");
$input_types[] = array (0 => 2, "form_type_id" => 2, 1 => "Birth date", "form_title" => "Birth date", 2 => "date" , "input_type" => "date");
$input_types[] = array (0 => 3, "form_type_id" => 3, 1 => "Sex", "form_title" => "Sex", 2 => "text" , "input_type" => "text");
$input_types[] = array (0 => 4, "form_type_id" => 4, 1 => "Address", "form_title" => "Address", 2 => "text" , "input_type" => "text");
$input_types[] = array (0 => 5, "form_type_id" => 5, 1 => "City", "form_title" => "City", 2 => "select" , "input_type" => "select");
$_POST[1] = 'John Smith';
$_POST[5] = 'Chicago';
//Loop over each entry to search for
foreach (array_keys($_POST) as $key ){
//Loop to the input array
foreach ($input_types as $search){
//If we find the right key, add it to the results array
if ($search['form_type_id'] == $key){
$results[$key] = $search['input_type'];
}
}
}
print_r($results);
答案 1 :(得分:0)
根据您的解释,您似乎想要X
数组中的每个键$_POST
:
$form_types
数组的成员,其中子成员具有键= form_type_id' and value matching
X`。V
的子成员的值2
。X => V
的成员。如果是这样,试试这个:
foreach ($_POST as $key => $val) {
$look_for = NULL;
foreach ($form_types as $form_type) {
if ($form_type['form_type_id'] == $key) {
$look_for = $form_type[2];
break;
}
}
$result[$key] = $look_for; // NULL if no match found
}