当前位置: 动力学知识库 > 问答 > 编程问答 >

php json decode issue

问题描述:

$data = json_decode($json,true);

echo $json;

When I use json_decode I get back a JSON tree like this:

[

"name",

[

"jason",

"carl",

"simpson",

"crew",

"marx"

]

]

So, how can I use foreach to get all the name values?

网友答案:

Like this:

<?php
$json = <<<JSON
[
    "name",
    [
        "jason",
        "carl",
        "simpson",
        "crew",
        "marx"
    ]
]
JSON;

$data = json_decode($json);

foreach($data[1] as $name) {
  echo "$name\n";
}
?>

Output:

$ php test.php
jason
carl
simpson
crew
marx

EDIT

Basically The json data is an array, where $data[0] is the value name, and $data[1] is a subarray that has the names you want

网友答案:
foreach ($data[1] as $name_value) {
    // do something with $name_value
}
网友答案:

If it was always the same structure, you could just loop over $data[1].

But it looks like it's some sort of key prefix structure. Then for reliability I'd use:

$key = array_search("name", $data);

if ($key !== FALSE)
foreach ($data[$key + 1] as $name) {
    print $name;
}
网友答案:

the $data variable now contains a 2-dimensional array. If you want to get an array of all the names, you say

$names=$data['name'];
分享给朋友:
您可能感兴趣的文章:
随机阅读: