如何根据特定元素的值有条件地删除子阵列?

时间:2016-02-04 17:07:22

标签: php arrays null filtering

我有一个包含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
    }
}

我希望有人能给我一些暗示。

2 个答案:

答案 0 :(得分:1)

->用于获取对象的属性。要从数组中获取值,请使用$array['key']表示法。

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

答案 1 :(得分:1)

您可以尝试这种方式,或者只使用@Mark Ba​​ker评论的array_filter()

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

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