【问题标题】:How to conditionally remove subarrays based on specific element's value?如何根据特定元素的值有条件地删除子数组?
【发布时间】:2017-08-03 14:26:42
【问题描述】:

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

希望有人能给我一点提示。

【问题讨论】:

  • if($vcpe['account_id'] == null)
  • $result = array_filter($originalArray, function($value) { return $value['account_id'] !== null; });

标签: php arrays null filtering


【解决方案1】:

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

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

【讨论】:

  • 我解码它,因此我使用箭头。抱歉更新我的帖子太慢了。但是你在回答我的问题。 :)
  • 我喜欢unset() 的建议。
【解决方案2】:

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

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

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

【讨论】:

  • 好建议,我将把它添加到我的 PHP 工具箱中。谢谢桑尼。
猜你喜欢
  • 2020-12-13
  • 2013-04-06
  • 1970-01-01
  • 2019-12-13
  • 2021-07-23
  • 2013-07-12
  • 2023-03-17
  • 1970-01-01
  • 2022-12-18
相关资源
最近更新 更多