2014-12-13 92 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