Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

php - 如何使用PHP解析JSON文件? [重复](How can I parse a JSON file with PHP? [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

I tried to parse a JSON file using PHP.

(我试图使用PHP解析JSON文件。)

But I am stuck now.

(但是我现在被困住了。)

This is the content of my JSON file:

(这是我的JSON文件的内容:)

{
    "John": {
        "status":"Wait"
    },
    "Jennifer": {
        "status":"Active"
    },
    "James": {
        "status":"Active",
        "age":56,
        "count":10,
        "progress":0.0029857,
        "bad":0
    }
}

And this is what I have tried so far:

(到目前为止,这是我尝试过的:)

<?php

$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);

echo $json_a['John'][status];
echo $json_a['Jennifer'][status];

But because I don't know the names (like 'John' , 'Jennifer' ) and all available keys and values (like 'age' , 'count' ) beforehand, I think I need to create some foreach loop.

(但是由于我事先不知道名称(例如'John''Jennifer' )和所有可用的键和值(例如'age''count' ),所以我认为我需要创建一些foreach循环。)

I would appreciate an example for this.

(我希望为此举一个例子。)

  ask by John Doe translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To iterate over a multidimensional array, you can use RecursiveArrayIterator

(要遍历多维数组,可以使用RecursiveArrayIterator)

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:
";
    } else {
        echo "$key => $val
";
    }
}

Output:

(输出:)

John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0

run on codepad

(在键盘上运行)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...