2014-12-13 91 views
0

我试图做到以下几点:从阵列$post_dataPHP基于匹配的密钥列表从关联数组获取值

  1. 抓斗键/值对...

  2. 只有在密钥与提供的列表匹配$my_fields ...

  3. 并创建一个只包含匹配数据的新数组。

例如,来自$post_data我想抓住键/值对的first_namelast_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 
//) 

回答

0

你应该使用这个。

foreach($post_data as $key=>$value){ 
    if(in_array($key,$my_fields)){ 
    $clean_data[$key]=$value; 
    } 
} 
print_r($clean_data); 

你正在朝正确的方向努力,只是在数组中的键的匹配必须以不同的方式。

+0

感谢@nitigyan,这工作完美。 – 2014-12-13 18:51:05

2

不需要循环 - 如果需要,可以在一行中完成。这里是神奇的功能:

如果你不想修改$ my_fields阵列可以用array_flip()

,并为进一步阅读all other fun你可以有与数组。

现在MARKY选择的答案,这里是例子如何可以通过以不同的方式进行:

$my_fields = array(
    'first_name', 
    'last_name', 
    'title' 
); 

$post_data = array(
    'first_name' => 'foo', 
    'last_name' => 'bar', 
    'title'  => 'Doctor', 
    'user_email' => '[email protected]' 
); 

$clean_data = array_intersect_key($post_data, array_flip($my_fields)); 

这将产生

array (
    'first_name' => 'foo', 
    'last_name' => 'bar', 
    'title'  => 'Doctor', 
) 
+0

你是否尝试运行你的代码,它是否给出了期望的结果? – nitigyan 2014-12-13 18:57:15

+0

您修改了$ my_fields数组本身以适合您的答案。这是一个数字索引数组。 – nitigyan 2014-12-13 18:58:58

+0

感谢您的回复。我只是试过你的方法,但我得到的是一个空的$ clean_data数组。我会重新阅读文档,试图弄清楚什么是错误的。再次感谢。 – 2014-12-13 19:01:16

0

你可以用你的foreach部分没有专柜需要更换

foreach ($post_data as $key => $value) 
{ 
    if (in_array($key,$my_fields)) 
    { 
     $clean_data[$key] = $value; 
    } 
} 
+0

只是在发布你的之前通过已经提交的答案。虽然你的回答是正确的,但我已经提交了相同的答案。 – nitigyan 2014-12-13 19:00:16

+0

对不起!我提交后看到它 – Aditya 2014-12-13 19:05:02