douxu0550 2013-01-25 16:31
浏览 121
已采纳

使用array_search和unset()与多维数组

I'm trying to search through a multi-dimensional array for a value called "test4". The array looks like this:

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
                )

        )

I found the following posts: Search a multidimensional array php

and

using array_search() to find values in php

and I'm using the rescursiveiterator method to find the value test4. My code looks like this:

foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($vlans)) as $key=>$value) {
    if ($value == 'test4') {
             print 'fount it. the key is: '. $key .' and value is: '. $value;
        break;
    }
}

This gives the following output:

fount it. the key is: 0 and value is: test4

I can't use this to unset the test4 record because [0] just unsets the first item in the outtermost array... in this case, it would remove VlanID 2, with the name test2.

can you help me figure out how to remove the record test4, once I've found it? I tried reading the following post:

Unsetting multi-dimensional arrays in php

but wasn't able to quite understand how to resolve this issue.

Thanks.

EDIT 1:

        foreach ($vlans as $a=>$value) {
            if ($value['Name'][0] =='test4' ){
                echo 'found it at: '. $value;
                unset($vlans[$a]);
                break;
            }   
          } 
  • 写回答

2条回答 默认 最新

  • dougongyou7364 2013-01-25 16:35
    关注

    Considering $array to be the outmost array:

    foreach ($array as $a) {
        if ($a['Name'][0]) == 'test4') { ... }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器