我试图做到以下几点:从阵列$post_data
PHP基于匹配的密钥列表从关联数组获取值
抓斗键/值对...
只有在密钥与提供的列表匹配
$my_fields
...并创建一个只包含匹配数据的新数组。
例如,来自$post_data
我想抓住键/值对的first_name
,last_name
,和title
而忽略user_email
。然后我想用这些键/值对创建一个名为$clean_data
的新阵列。
以下是我在循环$ 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' => '[email protected]'
);
$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
//)
感谢@nitigyan,这工作完美。 – 2014-12-13 18:51:05