drv54591 2013-09-26 17:46
浏览 27
已采纳

检查子数组的值,在新数组中使用key作为新值 - PHP

I have an array, let call it $mainArray, which looks like this: -

Array
(
    [1] => Array
    (
    )

    [5] => Array
    (
        [0] => 10
        [1] => 15
        [2] => 20
        [3] => 25
    )

    [80] => Array
    (
        [0] => 20
        [1] => 40
        [2] => 50
        [3] => 60
    )

    [777] => Array
    (
        [0] => 100
        [1] => 200
        [2] => 300
        [3] => 400
    )

    [666] => Array
    (
        [0] => 1234
        [1] => 5678
        [2] => 20
        [3] => 9865
    )

    [555] => Array
    (
        [0] => 111
        [1] => 222
        [2] => 333
        [3] => 444
    )

)

What I want to do is create 2 new arrays: -

1) Where values are equal to the key names of $mainArray, but only those where the sub-array (if there is one) contains the value "20" somewhere in it. For example my new array (call it $arrayOne) will be [0] => 5, [1] => 80, [2] => 666.

2) Similar to above, but where there's either no sub-array or, if there is, it doesn't include "20" as a value. So that (call it $arrayTwo) would be [0] => 1, [1] => 777, [2] =>555.

I've tried loads of for each loops and even a little RecursiveIteratorIterator (whatever that is!) but can't seem to reference keys and values in the way that I need to. Any help would be much appreciated!

  • 写回答

3条回答 默认 最新

  • doulongsi1831 2013-09-26 17:51
    关注

    Will this do?:

    <?php
    
        foreach( $mainArray as $mKey => &$mVal )
        {
            if( in_array( 20, $mVal ) )
            {
                $arrayOne[] = $mKey;
            }
            else
            {
                $arrayTwo[] = $mKey;
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到