如果找到此键,则在foreach循环上取消关联数组

时间:2019-01-16 07:50:40

标签: php codeigniter

我有一个数据数组,我想要的就是检查是否找到了这个键,因为如果是,我将取消设置某个数组

这是我的示例数组:

Array
(
  [2019-01-01] => Array(
     [1] => Array(
        ['OLD'] => Array(
          [0] => Array(
            ['id']=>1,
            ['name']=>full name
          )
        )
        ['NEW'] => Array(
          [0] => Array(
            ['id']=>2,
            ['name']=>full name
          )
        )
     )
  )
  [2019-01-02] => Array(
     [1] => Array(
        ['OLD'] => Array(
          [0] => Array(
            ['id']=>5,
            ['name']=>full name
          )
        )
     )
  )
)

我有此代码:

foreach ($my_array as $key=>$val) {
  foreach ($val as $key=>$val) {
    foreach ($val as $key=>$val) {
      // I wanted to check in this part if this array has `$key` OLD and `$key` NEW, if it has new then unset OLD
    }
  }
}

我的预期结果是如果有NEW,则要删除的OLD,但是如果没有NEW,则保留OLD数组。在这里使用正确的array函数是什么?

1 个答案:

答案 0 :(得分:2)

array_walk()可能会帮助您。示例:

array_walk($arr, function (&$item) {
    if(isset($item[1]['OLD'], $item[1]['NEW'])) unset($item[1]['OLD']);
});