2016-02-04 53 views
-1

我有13個元素如何根據特定元素的值有條件地刪除子陣列?

$vcpes= 
array:13 [▼ 
    0 => array:23 [▼ 
    "cpe_mac" => "665544332211" 
    "bandwidth_max_up" => 300000 
    "bandwidth_max_down" => 500000 
    "filter_icmp_inbound" => null 
    "dmz_enabled" => null 
    "dmz_host" => null 
    "vlan_id" => null 
    "dns" => [] 
    "xdns_mode" => null 
    "cfprofileid" => null 
    "stub_response" => null 
    "acl_mode" => null 
    "portal_url" => null 
    "fullbandwidth_max_up" => null 
    "fullbandwidth_max_down" => null 
    "fullbandwidth_guaranty_up" => null 
    "fullbandwidth_guaranty_down" => null 
    "account_id" => 1000 // <--- Keep 
    "location_id" => null 
    "network_count" => null 
    "group_name" => null 
    "vse_id" => null 
    "firewall_enabled" => null 
    ] 
    1 => array:23 [▼ 
    "cpe_mac" => "213243546576" 
    "bandwidth_max_up" => null 
    "bandwidth_max_down" => null 
    "filter_icmp_inbound" => null 
    "dmz_enabled" => null 
    "dmz_host" => null 
    "vlan_id" => null 
    "dns" => [] 
    "xdns_mode" => null 
    "cfprofileid" => null 
    "stub_response" => null 
    "acl_mode" => null 
    "portal_url" => null 
    "fullbandwidth_max_up" => null 
    "fullbandwidth_max_down" => null 
    "fullbandwidth_guaranty_up" => null 
    "fullbandwidth_guaranty_down" => null 
    "account_id" => null // <--- Delete 
    "location_id" => null 
    "network_count" => null 
    "group_name" => null 
    "vse_id" => null 
    "firewall_enabled" => null 
    ] 
    2 => array:23 [▶] 
    3 => array:23 [▶] 
    4 => array:23 [▶] 
    5 => array:23 [▶] 
    6 => array:23 [▶] 
    7 => array:23 [▶] 
    8 => array:23 [▶] 
    9 => array:23 [▶] 
    10 => array:23 [▶] 
    11 => array:23 [▶] 
    12 => array:23 [▶] 
] 

我想刪除具有account_id == null的那些陣列。

我試圖對其進行解碼:

$vcpes = json_decode (json_encode ($vcpes), FALSE);

,並檢查它:

foreach($vcpes as $vcpe){ 
    if($vcpe->account_id == null){ 
     //delete it 
    }else{ 
     //don't delete it 
    } 
} 

我希望有人可以給我一點提示這一點。

+0

'如果($ vcpe [ 'ACCOUNT_ID'] == NULL)'' –

+0

$結果= array_filter評論($ originalArray,function($ value){return $ value ['account_id']!== null;});' –

回答

1

->用於獲取對象的屬性。要從數組中獲取值,請使用$array['key']表示法。

foreach($vcpes as $i => $vcpe){ 
    if ($vcpe['account_id'] === null) { 
     unset($vcpes[$i]); 
    } 
} 
+0

我解碼它,因此我使用箭頭。抱歉更新我的帖子太慢了。但是你正在回答我的問題。 :) – ihue

+0

我喜歡'unset()'建議。 – ihue

1

你可以試試這個方法,或者只是使用array_filter()由@馬克·貝克

$finalArray = []; 
foreach($vcpes as $vcpe){ 
    if($vcpe->account_id != null){ 
     $finalArray[] = $vcpe; 
    } 
} 

print '<pre>'; 
print_r($finalArray); 
print '</pre>'; 
+0

好的建議,我會把它添加到我的PHP工具箱中。感謝Sunny。 – ihue

相關問題