PHP函数用路径获取递归路径键 [英] PHP function to get recursive path keys with path
本文介绍了PHP函数用路径获取递归路径键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个数组,我想要一个扁平版本的数组键.到那时,每个数组键都需要数组的路径",并附加下划线.
一个例子最好地解释了这一点.
$arr = array("location"=>0,"details"=>array("width"=>0,"height"=>0,"level"=>array(三"=> 0)));函数答案($arr){....}
答案函数会返回这个:
array("location","details_width","details_height","details_level_three");
更新:
这是正在进行的工作.它将接受一个数组并返回数组键,但没有深度:
function recursive_keys($input){$output = array_keys($input);foreach($input as $sub){if(is_array($sub)){$output = array_merge($output, recursive_keys($sub));}}返回 $output;}
解决方案
function recursive_keys(array $array, array $path = array()) {$result = array();foreach ($array as $key => $val) {$currentPath = array_merge($path, array($key));如果(is_array($val)){$result = array_merge($result, recursive_keys($val, $currentPath));} 别的 {$result[] = join('_', $currentPath);}}返回 $result;}
此处演示:http://codepad.viper-7.com/WQ3UYI>
Given an array, I would like a flattened version of the array keys. Each array key would need the 'path' of the array, to that point, appended with an underscore.
An example explains this best.
$arr = array("location"=>0,"details"=>array("width"=>0,"height"=>0,"level"=>array("three"=>0)));
function answer($arr) {....}
the answer function would return this:
array("location","details_width","details_height","details_level_three");
UPDATE:
Here is the work in progress. It will accept an array and return the array keys, but with no depth:
function recursive_keys($input)
{
$output = array_keys($input);
foreach($input as $sub){
if(is_array($sub)){
$output = array_merge($output, recursive_keys($sub));
}
}
return $output;
}
解决方案
function recursive_keys(array $array, array $path = array()) {
$result = array();
foreach ($array as $key => $val) {
$currentPath = array_merge($path, array($key));
if (is_array($val)) {
$result = array_merge($result, recursive_keys($val, $currentPath));
} else {
$result[] = join('_', $currentPath);
}
}
return $result;
}
Demo here: http://codepad.viper-7.com/WQ3UYI
这篇关于PHP函数用路径获取递归路径键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文