如何在php中删除数组中的元素[duplicate]

h7appiyu  于 2023-02-07  发布在  PHP
关注(0)|答案(2)|浏览(118)
    • 此问题在此处已有答案**:

Delete element from multidimensional-array based on value(7个答案)
3天前关闭。
我有下面的数组,其中包含json对象

[
  {
    "couponCode": "GanheOutro",
    "description": "Ganhe Outro",
    "status": "Active",
    "type": "EarnedProduct",
    "validProducts": {
      "posCodes": [
        "I11009",
        "I22749"
      ]
    },
    "limitedQuantity": 1,
    "couponRequired": 1,
    "discountCode": 378,
    "discountInfo": ""
  },
  {
    "couponCode": 593,
    "description": "Bebida de Aniversário",
    "status": "Active",
    "type": "Discount",
    "discount": 1,
    "limitedQuantity": 1,
    "couponRequired": 1,
    "discountCode": 247,
    "discountInfo": ""
  },
  {
    "couponCode": 594,
    "description": "Bebida 12 Estrelas",
    "status": "Active",
    "type": "Discount",
    "discount": 1,
    "limitedQuantity": 1,
    "couponRequired": 1,
    "discountCode": 248,
    "discountInfo": ""
  }
]

我需要删除couponCode = 594的元素,在本例中是最后一个Json,但我不知道如何在php中执行此操作

iugsix8n

iugsix8n1#

使用array_filter函数,可以获取couponCode值不等于594的项目

$json = json_decode('[
    {
      "couponCode": "GanheOutro",
      "description": "Ganhe Outro",
      "status": "Active",
      "type": "EarnedProduct",
      "validProducts": {
        "posCodes": [
          "I11009",
          "I22749"
        ]
      },
      "limitedQuantity": 1,
      "couponRequired": 1,
      "discountCode": 378,
      "discountInfo": ""
    },
    {
      "couponCode": 593,
      "description": "Bebida de Aniversário",
      "status": "Active",
      "type": "Discount",
      "discount": 1,
      "limitedQuantity": 1,
      "couponRequired": 1,
      "discountCode": 247,
      "discountInfo": ""
    },
    {
      "couponCode": 594,
      "description": "Bebida 12 Estrelas",
      "status": "Active",
      "type": "Discount",
      "discount": 1,
      "limitedQuantity": 1,
      "couponRequired": 1,
      "discountCode": 248,
      "discountInfo": ""
    }
  ]');

$result = array_filter($json, fn ($item) => $item->couponCode !== 594);

var_export($result);
qhhrdooz

qhhrdooz2#

以下是一些指导原则:
可以使用PHP中的array_filter函数来过滤数组并移除所需的元素。
array_filter函数有两个参数:原始数组和回调函数。如果元素应保留在过滤数组中,则回调函数应返回true;如果应删除该元素,则回调函数应返回false。在这种情况下,应使用匿名函数检查当前元素的couponCode是否不等于594。
(ofc为了完成所有这些,您应该首先将json数据放入一个数组中)

相关问题