PHP从多维数组

时间:2018-02-23 12:31:43

标签: php arrays

我有一个数组$arr,如下所示:

'sdb5' => [
    'filters' => [
        (int) 11 => [
            'find' => [
                (int) 0 => (int) 569
            ],
            'exclude' => [
                (int) 0 => (int) 89,
                (int) 1 => (int) 573
            ]
        ],
        (int) 86 => [
            'find' => [
                (int) 0 => (int) 49,
                (int) 1 => (int) 522,
                (int) 2 => (int) 803
            ],
            'exclude' => [
                (int) 0 => (int) 530,
                (int) 1 => (int) 802,
                (int) 2 => (int) 511
            ]
        ]
    ]
],

我已阅读Delete element from multidimensional-array based on value,但我正在努力了解如何以有效的方式删除值。

例如,假设我要删除值522。我是这样做的:

 $remove = 522; // value to remove

 foreach ($arr as $filters) {
     foreach ($filters as $filter) {
         foreach ($filter as $single_filter) {
             foreach ($single_filter as $key => $value) {
                 if ($value == $remove) {
                     unset($key);
                 }
             }
          }
      }
  }

我无法从上面的链接中解决这个问题,因为即使它是一个多维数组,它也没有像我这样的子数组。

我也不知道如何重写这个而不重复foreach来获取我想要的数组元素。我再次阅读Avoid multiple foreach loops但不能将其应用于我的数组。

任何建议都将受到赞赏。

使用PHP 7.x

3 个答案:

答案 0 :(得分:1)

foreach()制作了元素副本。然后unset键是不够的,因为你正在销毁一个局部变量。

您可以在&循环和foreach()中使用引用unset,如:

 foreach ($arr as &$filters) {
     foreach ($filters as &$filter) {
         foreach ($filter as &$single_filter) {
             foreach ($single_filter as $key => $value) {
                 if ($value == $remove) {
                     unset($single_filter[$key]);
                 }
             }
          }
      }
  }

或使用密钥($k1$k2,...):

 foreach ($arr as $k1 => $filters) {
     foreach ($filters as $k2 => $filter) {
         foreach ($filter as $k3 => $single_filter) {
             foreach ($single_filter as $key => $value) {
                 if ($value == $remove) {
                     unset($arr[$k1][$k2][$k3][$key]);
                 }
             }
          }
      }
  }

答案 1 :(得分:1)

你也可以写一个递归函数,所以你不必使用嵌套的foreach

function deleteRecursive(&$array, &$value) {
  foreach($array as $key => &$subArray) {
    if(is_array($subArray)) {
      deleteRecursive($subArray, $value);
    } elseif($subArray == $value) {
      unset($array[$key]);
    }
  }
}

$valueToDelete = 522;

deleteRecursive($array, $valueToDelete);

答案 2 :(得分:0)

function recursiveRemoval(&$array, $val)
{
    if(is_array($array))
    {
        foreach($array as $key=>&$arrayElement)
        {
            if(is_array($arrayElement))
            {
                recursiveRemoval($arrayElement, $val);
            }
            else
            {
                if($arrayElement == $val)
                {
                    unset($array[$key]);
                }
            }
        }
    }
}

通话功能

recursiveRemoval($array, $value);