使用 PHP 循环访问未知的 Json 文件



我知道如何使用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);

更改每个数组中每个值的最佳臂是使用array_walk_recursive()。因此,您可以按照自己的方式使用它。下面是一个示例:

<?php
$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_array = json_decode($json, true);
array_walk_recursive(
$json_array,
function (&$value, $key) {
// You may put conditions here if you need
$value = $value . ' New value';
}
);
var_dump($json_array);

创建一个递归函数,不断挖掘:

<?php
$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"
}
}
}
}
}';
$array = json_decode($json, true);
function changeValsDeep($array, $func){
$a = [];
foreach($array as $k => $v){
if(is_array($v)){
$a[$k] = changeDeep($v, $func);
}
else{
$a[$k] = $func($k, $v);
}
}
return $a;
}
function changeAll(){
return 'Why would you want to do this?';
}
function keyBasedChange($key, $val){
if($key === 'Level 3_2'){
return 'Oh look, it works!';
}
return $val;
}
function valueBasedChange($key, $val){
if($val === 'More text'){
return 'You can make the value what you want now!';
}
return $val;
}
print_r(changeValsDeep($array, 'changeAll'));
print_r(changeValsDeep($array, 'keyBasedChange'));
print_r(changeValsDeep($array, 'valueBasedChange'));
?>

最新更新