拥有此数组(作为JSON):
{
"token_name": "C_ROOT",
"token_group": "C_BLOCK",
"group": true,
"body": [
[
{
"token_name_org": "T_VARIABLE",
"token": 320,
"value": "sort",
"line": 2,
"token_group": "VARIABLES",
"token_name": "C_VARIABLE"
},
{
"token_name_org": "C_ASSIGNMENT_EQUAL",
"line": 2,
"value": "=",
"token": "VALUE",
"token_group": "ASSIGNMENTS"
},
{
"token_name_org": "T_VARIABLE",
"token": 320,
"value": "_GET",
"line": 2,
"token_group": "VARIABLES",
"token_name": "C_VARIABLE",
"args": [
[
{
"token_name_org": "T_CONSTANT_ENCAPSED_STRING",
"token": 323,
"value": "sort",
"line": 2,
"token_group": "STRINGS",
"token_name": "C_STRING"
}
]
]
}
]
]
}
编写此代码以搜索关键“值”为“排序”。
public function search_var($array,$var)
{
foreach($array as $key=>$value)
{
if(is_array($value))
{
$this->search_var($value,$var);
}else{
if(isset($array["value"]) && $array["value"] == $var)
{
print $value."\n";
}
}
}
}
print_r($scanner->search_var($map,"sort"));
不知道如何在我的代码中引用兄弟姐妹和孩子?即
现在输出是:
T_VARIABLE
320
sort
2
VARIABLES
C_VARIABLE
如何才能将其视为仅作为输出:
/sort/=/_GET/sort
“/”之间的每个值都是兄弟姐妹或孩子的关键“值”(最后一种情况)
谢谢,
答案 0 :(得分:1)
当问题body
包含的信息多于问题中发布的信息时,问题还不清楚。这个答案假定它永远不会。
可能的解决方案是使用array_walk_recursive()
并将与value
键关联的值收集到数组中。散步后,使用所需的分隔符(/
)简单地连接收集的值:
$text = '{"token_name":"C_ROOT","token_group":"C_BLOCK","group":true,"body":[[{"token_name_org":"T_VARIABLE","token":320,"value":"sort","line":2,"token_group":"VARIABLES","token_name":"C_VARIABLE"},{"token_name_org":"C_ASSIGNMENT_EQUAL","line":2,"value":"=","token":"VALUE","token_group":"ASSIGNMENTS"},{"token_name_org":"T_VARIABLE","token":320,"value":"_GET","line":2,"token_group":"VARIABLES","token_name":"C_VARIABLE","args":[[{"token_name_org":"T_CONSTANT_ENCAPSED_STRING","token":323,"value":"sort","line":2,"token_group":"STRINGS","token_name":"C_STRING"}]]}],[{"token_name_org":"T_VARIABLE","token":320,"value":"mort","line":2,"token_group":"VARIABLES","token_name":"C_VARIABLE"},{"token_name_org":"C_ASSIGNMENT_EQUAL","line":2,"value":"=","token":"VALUE","token_group":"ASSIGNMENTS"},{"token_name_org":"T_VARIABLE","token":320,"value":"_GET","line":2,"token_group":"VARIABLES","token_name":"C_VARIABLE","args":[[{"token_name_org":"T_CONSTANT_ENCAPSED_STRING","token":323,"value":"mort","line":2,"token_group":"STRINGS","token_name":"C_STRING"}]]}]]}';
$array = json_decode($text, TRUE);
// Collect the values here.
// Start with an empty string to force a leading '/' in the output
$path = array('');
// Walk the array, put the desired values in $path
array_walk_recursive(
$array,
function($value, $key) use (&$path) { // use reference to modify $path inside the function
if ($key == 'value') {
$path[] = $value;
}
}
);
// Join the collected values and output the result
echo(implode('/', $path));
答案 1 :(得分:0)
你的问题措辞非常严厉,但我相信你正在努力实现这个目标:
public function search_var($array,$var) {
foreach($array as $key=>$value) {
if(is_array($value)) {
$this->search_var($value,$var);
} elseif($key == $var) {
print "/".$value;
}
}
}