[英]PHP Get values from associative array based on list of matched keys
I'm trying to do the following: 我正在尝试执行以下操作:
Grab key/value pairs from an array $post_data
... 从数组
$post_data
键/值对...
Only where the key matches a provided list $my_fields
... 仅在键与提供的列表
$my_fields
匹配的$my_fields
...
And create a new array with only the matched data. 并创建一个仅包含匹配数据的新数组。
For example, from $post_data
I'd like to grab the key/value pairs for first_name
, last_name
, and title
while ignoring user_email
. 例如,我想从
$post_data
中获取first_name
, last_name
和title
的键/值对,而忽略user_email
。 I'd then like to create a new array named $clean_data
with these key/value pairs. 然后,我想使用这些键/值对创建一个名为
$clean_data
的新数组。
Below is my failed attempt at looping through the $post_data array and pulling out the matches based on the $my_fields array. 下面是我在遍历$ post_data数组并基于$ my_fields数组提取匹配项时的失败尝试。
// These are the fields I'd like to get from the $post_data array
$my_fields = array(
'first_name',
'last_name',
'title'
);
// This is the raw data. I do not need the 'user_email' key/value pair.
$post_data = array(
'first_name' => 'foo',
'last_name' => 'bar',
'title' => 'Doctor',
'user_email' => 'fb@gmail.com'
);
$clean_data = array();
$counter == 0;
foreach ($post_data as $key => $value)
{
if (array_key_exists($my_fields[$counter], $post_data))
{
$clean_data[$key] = $value;
}
$counter++;
}
// Incorrectly returns the following: (Missing the first_name field)
// Array
// (
// [last_name] => bar
// [title] => Doctor
// )
No looping needed - you can have it all done in one line if you want. 无需循环-如果需要,您可以将所有操作都在一行中完成。 Here is the magic function:
这是魔术函数:
And if you don't want to modify your $my_fields array you can use array_flip() 而且,如果您不想修改$ my_fields数组,则可以使用array_flip()
And for further reading all other fun you can have with arrays. 为了进一步阅读所有其他乐趣,您可以使用数组。
Now that MARKY chose the answer, here is the example how it could be done by differently: 现在,MARKY选择了答案,下面是示例如何通过不同方式完成的示例:
$my_fields = array(
'first_name',
'last_name',
'title'
);
$post_data = array(
'first_name' => 'foo',
'last_name' => 'bar',
'title' => 'Doctor',
'user_email' => 'fb@gmail.com'
);
$clean_data = array_intersect_key($post_data, array_flip($my_fields));
this produces 这产生
array (
'first_name' => 'foo',
'last_name' => 'bar',
'title' => 'Doctor',
)
You should use this. 您应该使用此。
foreach($post_data as $key=>$value){
if(in_array($key,$my_fields)){
$clean_data[$key]=$value;
}
}
print_r($clean_data);
You are trying in the right direction, just the matching of key in the array has to be in a different way. 您尝试的方向是正确的,只是数组中键的匹配必须采用不同的方式。
you can replace it with your foreach section no counter needed 您可以将其替换为您的foreach部分,而无需计数器
foreach ($post_data as $key => $value)
{
if (in_array($key,$my_fields))
{
$clean_data[$key] = $value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.