php - 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 数组有多“深”?
解决方案
尝试使用递归函数:
<?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”
推荐阅读
- design-patterns - 哪种类型的实现会更适合服务层?
- azure - Azure WebRole 粘性负载平衡
- kubernetes - istio-proxy 访问日志是什么意思?
- vb.net - 检查数组中每个文本框的标签
- android - Android:“发送到 SYSTEM 的 Binders 太多”是什么意思?
- python - (Python)如何在“实时”中将变量从 file1.py 传递到 file2.py?
- java - 通过在 java 中定期进行 Web 服务调用来更新 sqlite 数据库
- javascript - 为什么使用 jquery.find(":input") 添加动态输入时无法获取输入元素?
- git - 执行请求的更改而不是拉取请求的所有者
- git - git - 将分阶段的更改提交到另一个分支并合并