php json decode issue

439
$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 useforeach to get all the name values?

640

Answer

Solution:

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

203

Answer

Solution:

foreach ($data[1] as $name_value) {
    // do something with $name_value
}
596

Answer

Solution:

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;
}
512

Answer

Solution:

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'];

People are also looking for solutions to the problem: I want to change detail.php?id=4 to detail/4,but my .htaccess file not working

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.