我知道如何使用PHP遍历已知的Json结构。当前的问题是,我需要遍历文件的每个Json元素并更改其值,最后将其保存。并且我不知道预先文件的结构。我的代码需要适应文件的内容。此Json文件将深入几个级别,如下所示:
{
"Level 1": "Some text here",
"Level 2": {
"Level 3": {
"Level 3_1" : "More text",
"Level 3_2" : "Another value",
"Level 4": {
"Level 5": {
"Level 5_1": "Something here",
"Level 5_2": "Something else here"
}
}
}
}
}
某些元素没有与它们关联的文本的事实使我感到震惊。我的代码当前涵盖了Json内容的许多层次,但是它是可怕的代码,我敢肯定有一种高效,智能的方法可以用PHP做到这一点,但我只是找不到。
这是我目前的状态:
$file = file_get_contents($myfile);
$json = json_decode($file, true);
foreach($json as $key=>$value) {
if(is_array($value)) {
foreach ($value as $Key2=>$value2) {
//And son on ...
}
} else echo $value;
}
所以这可能会变得很无聊,而且如果文件中突然有一个额外的深度级别,我的代码将不会解析每个元素。如何实现呢?
您可以使用递归来做这样的事情:
function echoData($array)
{
foreach($array as $k=>$v)
{
if(is_array($v))
{
return echoData($v);
}
else {
echo $v.'-';
}
}
}
$array=[
"Level 1"=> "Some text here",
"Level 2"=> [
"Level 3"=> [
"Level 3_1" => "More text",
"Level 3_2" => "Another value",
"Level 4"=> [
"Level 5"=> [
"Level 5_1"=> "Something here",
"Level 5_2"=> "Something else here"
]
]
]
]
];
$array= json_decode(json_encode($array), true);
echoData($array);