[英]using array_search and unset() with multidimensional array
我正在尝试在多维数组中搜索名为“test4”的值。 该数组如下所示:
Array
(
[0] => Array
(
[VlanId] => Array
(
[0] => 2
)
[Name] => Array
(
[0] => test2
)
)
[1] => Array
(
[VlanId] => Array
(
[0] => 3
)
[Name] => Array
(
[0] => test3
)
)
[2] => Array
(
[VlanId] => Array
(
[0] => 4
)
[Name] => Array
(
[0] => test4
)
)
我找到了以下帖子: 搜索多维数组php
和
我正在使用rescursiveiterator方法来查找值test4。 我的代码看起来像这样:
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($vlans)) as $key=>$value) {
if ($value == 'test4') {
print 'fount it. the key is: '. $key .' and value is: '. $value;
break;
}
}
这给出了以下输出:
安慰它。 关键是:0和值是:test4
我无法使用它来取消设置test4记录,因为[0]只是取消设置outtermost数组中的第一项...在这种情况下,它将删除名为test2的VlanID 2。
你找到它之后能帮我弄清楚如何删除记录test4吗? 我试过阅读以下帖子:
但是不能完全理解如何解决这个问题。
谢谢。
编辑1:
foreach ($vlans as $a=>$value) {
if ($value['Name'][0] =='test4' ){
echo 'found it at: '. $value;
unset($vlans[$a]);
break;
}
}
考虑将$array
作为最外层的数组:
foreach ($array as $a) {
if ($a['Name'][0]) == 'test4') { ... }
}
这是一个更强大的解决方案,可以在任何多维数组上工作并返回关键路径的数组。 它在$haystack
搜索$haystack
$needle
并返回一个键路径数组(如果在数组中找到),否则返回false
。
function arraySearchRecursive($needle, $haystack, $strict=false, $path=array()) {
if(!is_array($haystack)) {
return false;
}
foreach ($haystack as $key => $val) {
if(is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path)) {
$path = array_merge($path, array($key), $subPath);
return $path;
} elseif ((!$strict && $val == $needle) || ($strict && $val === $needle)) {
$path[] = $key;
return $path;
}
}
return false; // value not in array!
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.