【问题标题】:JSON unset element at specific index in phpphp中特定索引处的JSON未设置元素
【发布时间】:2021-09-20 03:03:46
【问题描述】:

我有两个正在使用的 REST 网址。第一个有事件配置文件,在我的代码中,我循环并搜索第二个休息网址中的每一个。

【问题讨论】:

  • 如果您使用foreach 而不是for 循环遍历数组元素,事情会变得容易得多。
  • unset($eventRuleID); 不会取消设置数组中的任何内容。这有什么意义?
  • unset($policyPayloadCopy["EventProfile"][$counter]["EventRuleIDList"]["EventRuleID"][$index]); 是取消设置数组元素的方式。
  • 更好的方法是使用array_filter(),以保留严重性在$checkedArr 中的数组元素。
  • 如果你这样做$a = 1; $b = $a; unset($b);,它只会取消设置$b,而不是$a

标签: php json rest unset


【解决方案1】:

使用array_filter() 保留符合过滤条件的元素,而不是在循环期间取消设置元素。

foreach ($policyPayloadCopy["EventProfile"] as &$profile) {
    if (count($profile["EventRuleIDList"]["EventRuleID"]) > 1) {
        $profile["EventRuleIDList"]["EventRuleID"] = array_filter($profile["EventRuleIDList"]["EventRuleID"], function($rule) use ($checkedArr) {
            return in_array($rule["Severity"], $checkedArr);
        });
    }
}

引用变量&$profile 表示对$profile["EventRuleIDList"]["EventRuleID"] 的赋值会影响原始$policyPayloadCopy 数组而不是副本。

【讨论】:

    猜你喜欢
    • 2013-05-24
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 2017-08-06
    • 2021-12-26
    • 2015-10-13
    • 2014-03-09
    • 1970-01-01
    相关资源
    最近更新 更多