在PHP中查找未知多级数组中的键的值
我在数据库中有一个use定义的json字符串 JSON字符串有很多级别。我知道我的用户将定义一个名为“basevalue”的kay,并将其放在json中的某个位置 问题是,我事先不知道它将放在JSON中的什么位置,每次使用都可能放在数组中的不同位置,可能在不同的级别 以下是用户保存的JSON数据示例:在PHP中查找未知多级数组中的键的值,php,json,Php,Json,我在数据库中有一个use定义的json字符串 JSON字符串有很多级别。我知道我的用户将定义一个名为“basevalue”的kay,并将其放在json中的某个位置 问题是,我事先不知道它将放在JSON中的什么位置,每次使用都可能放在数组中的不同位置,可能在不同的级别 以下是用户保存的JSON数据示例: { "name": "", "type": "layout", "children": [ { "name": "", "type": "section
{
"name": "",
"type": "layout",
"children": [
{
"name": "",
"type": "section",
"children": [
{
"name": "",
"type": "row",
"children": [
{
"name": "",
"type": "column",
"props": {
},
"children": []
},
{
"type": "column",
"children": [
{
"type": "itemdata",
"props": {
**"basevalue": "100",**
},
"children": []
}
]
}
]
}
]
}
我正在使用json_decode将此数据转换为数组:
$json = json_decode($json, true);
不,我需要搜索整个数组,找到'basevalue'的键,然后得到用户输入的任何值,在上面的例子中是'100'
所以问题是,我不知道“basevalue”键是什么节点。它可能有40深,可能在第一个“子节点”中
这取决于用户
那么,如何获取任意版本的JSON字符串并返回“100”
非常感谢。您可以对数据进行递归迭代,并获得键
basevalue
的值。为了加快搜索速度,我们可以采用类似于的提前退出方法。这样,我们调用addall values来添加队列中的数组,并继续搜索keybasevalue
,然后再处理挂起的队列。这将比基本递归更快,因为很多时候,键可能位于同一级别,但我们一直搜索所有其他树,结果证明这些树都很平凡
片段:
function getBaseValue($arr,$search_key){
$pending_calls = [];
foreach($arr as $key => $value){
if(is_array($value)){
$pending_calls[] = $value; // queue them for later judgement
}else if($search_key === $key){
return $value;
}
}
foreach($pending_calls as $call){
$returned_val = getBaseValue($call,$search_key);
if($returned_val !== false) return $returned_val;
}
return false;
}
echo getBaseValue($arr,'basevalue');
演示:直到回调函数获得所需的密钥。无解码:
$chunk1=explode(“\'basevalue\”:”,$json)$chunk2=explode(“,”,$chunk1[1])$chunk3=trim($chunk2[0],“”);echo$chunk3;