StudioTime
StudioTime

Reputation: 23959

Decoding JSON array

I'm struggling to parse a simple JSON array, am new to this so trying to learn.

Here's the data:

{"data":[
  {"name":"john","id":"123"},
  {"name":"dave","id":"345"}
  ], "other":
  {"foo":"bar"}
}

I only want the data information.

Here's what I'm trying (also what else I tried):

$list = json_decode(file_get_contents($jsonURL),true);

foreach ($list as $element){

  //$id = $element->data->id; // this didn't work either
  //$name = $element->data->name; // this didn't work either

  $id = $element[data][id];
  $name = $element[data][name];

  $message .= $id.' - '.$name.'</br>';

}

Any ideas why it returns nothing?

Upvotes: 1

Views: 140

Answers (3)

worldofjr
worldofjr

Reputation: 3886

I'm surprised that everyone is telling you to access the data using arrays. JSON is a object based system, and you should access the data with the object notation. The problem was you were attempting to traverse the main object, not the data part of it.

You should do the following instead;

$list = json_decode(file_get_contents($jsonURL),true);
$data = $list->data;

foreach ($data as $element) {
    $id = $element->id;
    $name = $element->name;

    $message .= $id.' - '.$name.'</br>';
}

Hope this helps.

Upvotes: 0

Aleksey Linetskiy
Aleksey Linetskiy

Reputation: 473

First of all, you have errors in your code. Use strings to access members of the $element: $element['data']. Then, I would think that the entire data structure will be the first element of the list, so you can access it like this:

$list = json_decode(file_get_contents($jsonURL),true);
$data = $list['data'];

$id = $data['id'];
$name = $data['name'];

$message .= $id.' - '.$name.'</br>';

Upvotes: 0

morissette
morissette

Reputation: 1099

$json = '{"data":[
  {"name":"john","id":"123"},
    {"name":"dave","id":"345"}
      ], "other":
        {"foo":"bar"}
}';

$list = json_decode($json,true);
foreach ( $list['data'] as $item ) {
    echo $item['id'] . "\n";
    echo $item['name'] ."\n\n";
}

Here is a perfect example of how to work with that data.

Upvotes: 4

Related Questions