首页 > 解决方案 > php在数组中查找项目维度

问题描述

在数组中查找项目级别(深度);

嗨,我是 php 的新手,我找不到任何方法来查找数组项所在的维度。例如:

array=>[
  'name'=>'jack'
  , 'age'=>'18'
  , 'info'=>[
    'address'=>'bla bla bla'
    , 'email'=>'example@bla.com'
  ]
]

function findDepth($key)
{
  // do something
}

$result = findDepth('email');

$result // int(2)

上面的数组具有名为 email 的键,并且 email 键位于数组的第二级。是否有任何功能或方法或方法可以找到这个级别。

我找到了一个告诉你数组有多深的方法:有没有办法找出 PHP 数组有多“深”?

标签: phparrays

解决方案


尝试使用递归函数:

<?php

$array = [
    'name'=>'jack', // Level 0
    'age'=>'18',
    'info'=>[ // Level 1
        'address'=>'bla bla bla',
        'contacts' => [ // Level 2
            'email'=>'example@bla.com'
        ],
    ],
];

function getArrayKeyDepth(array $array, $key, int $currentDepth = 0): ?int
{
    foreach($array as $k => $v){
        if ($key === $k) {
            return $currentDepth;
        }
        
        if (is_array($v)) {
            $d = getArrayKeyDepth($v, $key, $currentDepth + 1);
            
            if ($d !== null) {
                return $d;
            }
        }
    }
    
    return null;
}

echo "Result:  ". getArrayKeyDepth($array, 'email');

这会给你“结果:2”


推荐阅读