douhan9748 2014-12-15 06:15
浏览 13
已采纳

相交的多维键

Say I have two arrays:

$array1

Array
(
    [app] => Array
        (
            [name] => PunchClock
            [shifts] => Array
                (
                    [maxhours] => 16
                    [minhours] => 4
                )

            [con] => Array
                (
                    [moog] => 3
                )

        )

)

and $array2

Array
(
    [app] => Array
        (
            [name] => 
        )

)

I'm trying to find a way use the second array in order to get its corresponding value coming from the first array. For example, if I were to call:

$value = $array2['app']['name']

The corresponding value would be PunchClock. If I were to choose $array2['app']['shifts'], the corresponding value would return an array containing maxhours and minhours. I've tried intersecting the arrays but not getting anywhere. I've running this in recursion but it's getting quite messy. I don't know what other options to use at this point. Any help would be appreciated.

  • 写回答

3条回答 默认 最新

  • doubu1853 2014-12-15 06:31
    关注
    function array_intersect_keys_recursive($a, $b)
    {
        $r = array();
        foreach ($a as $k => $v)
        {
            if (is_array($a[$k]) && isset($b[$k]) && is_array($b[$k]))
            {
                $r[$k] = array_intersect_keys_recursive($a[$k], $b[$k]);
                continue;
            }
            if (isset($a[$k]) && isset($b[$k]))
            {
                $r[$k] = $a[$k];
            }
        }
        return $r;
    }
    
    $a = Array
    (
        'app' => Array
            (
                'name' => 'PunchClock',
                'shifts' => Array
                    (
                        'maxhours' => 16,
                        'minhours' => 4
                    ),
    
                'con' => Array
                    (
                        'moog' => 3
                    )
    
            )
    
    );
    
    $b = Array
    (
        'app' => Array
            (
                'name' => ''
            )
    );
    
    
    $c = array_intersect_keys_recursive($a, $b);
    
    print_r($c);
    

    The above example will output:

    Array
    (
        [app] => Array
            (
                [name] => PunchClock
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 touchsocket udp组播
  • ¥20 MAC怎么安装Silverlight 插件?以及安装了怎么启用
  • ¥15 VS2012中查询语句无法填入解析,数值传不进去
  • ¥15 gis系统开发出现命名空间“ESRI.ArcGIS”中不存在类型或命名空间名“Analyst3D”报错
  • ¥15 怎么让ai定时给我发信息 c#或者python
  • ¥15 scrapy的Error
  • ¥15 RBF-VSG姚凤军论文复现问题
  • ¥30 开发一个APP商城在制作tabbar的时候运行不了代码没有检查出错误,但是显示不出tabbar,以下为运行结果,如何解决?
  • ¥15 多网卡服务器中winform如何绑定指定网卡
  • ¥15 关于#python#pandas#的问题,想要实现:多个TXT导入Excel,进行分列,不同txt之间都从第一行开始,请各位专家解答!