gpt4 book ai didi

php - 在 PHP 中查找层次结构中的父键

转载 作者:搜寻专家 更新时间:2023-10-31 21:02:41 28 4
gpt4 key购买 nike

$arrayArray 结构如下。

Array
(
[WIDGET_BUILDER_CREATE] => Array
(
[TITLE] => Widget Builder
[WIDGET_TYPE_LBL] => Select Widget Type
[RANGE_LBL] => Select Range
[RANGE_TYPE_LBL] => Select Range Type
[TOP_SERVICE_CHKBOX] => Top Services
[SR_STATE_LBL] => Select Sr States
[SR_TYPE_LBL] => Select Sr Types
[SR_CATEGORY_LBL] => Select Sr Categories
[SR_SOURCE_LBL] => Select Sources
[SR_PROVIDER_LBL] => Select Sr Provider
[ADDRESS] => Enter Address
[SUBMIT_BTN] => Generate Data
[CHART_DIV] => Array
(
[TYPE] => Select chart type
[SAVE_BTN] => Save Widget
[SERIES_NAME] => Change Parameters
[PARA_DIALOG] => Array
(
[TITLE] => Chart Parameters
[SERIESNAME] => Series Name
[YAXISNAME] => Y axies name
[VALIDATION] => Array
(
[SERIESNAME] => Please enter series name
[YAXISNAME] => Please enter y axis name
)

[SAVE_BTN] => Save
[CANCEL_BTN] => Cancel
)

[SAVE_DIALOG] => Array
(
[TITLE] => Save Chart
[CHART_NAME] => Chart Name
[SHOW_TO_USER] => System Widget
[VALIDATION] => Array
(
[CHART_NAME] => Please enter chart name
)

[SAVE_BTN] => Save
[CANCEL_BTN] => Cancel
)

)

[GRID_DIV] => Array
(
)

)

)

问题:

我想在 PHP 中构建一个函数,如果我输入一个值,那么它应该返回层次结构中的所有父键。

比方说,如果我输入Please enter y axis name,它应该返回为

$array['WIDGET_BUILDER_CREATE']['CHART_DIV']['PARA_DIALOG']['VALIDATION']['YAXISNAME'];

编辑: 我试过 How to get hierarchy path of an element in an Array但它以字符串形式返回,但我希望作为索引的数组键。这意味着

print_r($array['WIDGET_BUILDER_CREATE']['CHART_DIV']['PARA_DIALOG']['VALIDATION']['YAXISNAME']);

//returns Please enter y axis name

我正在使用 PHP 5.5.9

最佳答案

下面的函数搜索 $source 数组并返回一个数组,其中包含 $target 值的所有匹配路径。如果在 $source 中找不到该值,则返回一个空数组。

function pathFinder($target, array $source, $parentPath=''){
$results=[];
foreach($source as $k => $v){
$path = $parentPath.'/'.$k; //current path
//if element is array, recurse and import found results
if(is_array($v) && $result=pathFinder($target, $v,$path)){
foreach($result as $r) array_push($results,$r);
}
//else add element to results if it matches $target
elseif($v===$target) $results[]=$path;
}
return $results;
}

用法:

$target = 'Please enter axis Y name';
$foundPaths = pathFinder($target, $array);

Live demo

关于php - 在 PHP 中查找层次结构中的父键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38867572/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com