2014-04-23 79 views
0

這是下面另一個問題的後續問題;從關聯數組陣列中過濾所選元素

Removing selected elements from array of associative arrays

這一次,我想從關聯數組的數組過濾選定的元素,而不是刪除它們。我有這個數組;我有此數組;

$result = array(
    (int) 0 => array(
     'name' => 'Luke', 
     'id_number' => '1111', 
     'address' => '1544addr', 
     'time_here' => '2014-04-12 13:07:08' 
    ), 
    (int) 1 => array(
     'name' => 'Sam', 
     'id_number' => '2222', 
     'address' => '1584addr', 
     'time_here' => '2014-04-12 14:15:26' 

我想過濾這個數組中的選定元素,使它看起來像這樣;

array(
    (int) 0 => array(
     'name' => 'Luke', 
     'id_number' => '1111' 
    ), 
    (int) 1 => array(
     'name' => 'Sam', 
     'id_number' => '2222' 

對於刪除元素,函數unset派上用場。但是如果我想過濾選定的元素呢?代碼如何看起來像?

謝謝。

回答

1

試試這個

// $result is your input array 
    $arr_filter_keys = array("name", "id_number"); // array of keys to be filter 
    $arr_filter_result = array(); // output array 
    foreach($result as $key=>$arr) 
    { 
     foreach($arr_filter_keys as $filter_key) 
     { 
      $arr_filter_result[$key][$filter_key] = $arr[$filter_key]; 
     } 
    } 

    print_r($arr_filter_result); // output array 

Demo-1

更新2:

我F你想導致同一陣列

// $result is your input array 
    $arr_filter_keys = array("name", "id_number"); // array of keys to be filter 

    foreach($result as $key=>$arr) 
    { 
     foreach($arr as $k=>$v) 
     { 
     if(!in_array($k, $arr_filter_keys)) 
     { 
      unset($result[$key][$k]); 
     } 
     } 
    } 

    print_r($result); // output array 

Demo-2

+0

感謝。在我看來,Demo-1將比Demo-2運行得更快,對吧? – user781486

+0

因爲在demo-1中沒有檢查'in_array'的if條件 –

0

之前unset將它們保存在另一個數組中。

$filtered = array(); 
foreach($arr as $key=>$val){ 
    $filtered[$key]['address'] = $val['address']; 
    $filtered[$key]['time_here'] = $val['time_here']; 
    unset($arr[$key]['address'],$arr[$key]['time_here']); 
} 

Demo

1

您可以使用此;

function filterArr(&$arr, $keys_to_be_filtered) { 
    foreach($arr as $key => $value) 
    { 
     foreach($keys_to_be_filtered as $key_to_remove) { 
      unset($arr[$key][$key_to_remove]); 
     } 
    } 
} 

filterArr($result, array("address", "time_here")); 

這裏是一個工作演示:Demo