2017-03-07 78 views
0

以下的輸出使$new_array包含多個陣列,其中iddatetype

$new_array = array(); 

foreach($things as $thing)(

    $new_array[] = array(
     'id' => $thing['id'], 
     'date' => '2017-01-01', 
     'type' => $thing['type'] 
    ); 

) 

如果我print_r($new_array)這讓我所有的數組裏面,但後來我想修改這個數組,並刪除所有沒有具體type其內部陣列。

爲此,我假設我需要取消設置任何$new_array[]陣列,其中鍵值對type =>等於x

我該如何實現這個目標?我已經閱讀了未設置的鍵值對,但這並不能幫助我處理多個數組。

+1

['$ new_array = array_filter($ new_array,函數($ N){返回$ N [ '型'] == 'X' ;});'](http://php.net/manual/en/function.array-filter.php)? – castis

+0

只需檢查'$ thing ['type']'是否等於x,如果是,甚至不要將該子數組添加到數組中。如果你想過濾數組,你可能想使用'array_filter()'或者用一個簡單的foreach循環和'unset()'來完成。 – Rizier123

+0

什麼是$東西? – Datadimension

回答

0

也許你應該先檢查加入陣列之前:

foreach($things as $thing){ 
    if(!empty($thing['type']) && $thing['type'] == 'my type'){ 
    $data[] = [ 
     'id' => $thing['id'], 
     'date' => '2017-01-01', 
     'type' => $thing['type'] 
    ]; 
    } 
} 

print_r($data);