mike
mike

Reputation: 65

Json how to display an information

How to display name ?

I tryiedthis but it does'nt work : $result_content_module->authors->name

var_dump($result_content_module->authors) has the value of authors also $result_content_module->title

{
 "title":   "Archive",
 "authors": [
  {
   "name": "MyName",
   "company":   "Company",
   "email": "emailopping.org",
   "website":   "website"
  }
 ]
}

Upvotes: 1

Views: 47

Answers (3)

Shahnawaz Kadari
Shahnawaz Kadari

Reputation: 1571

authors is an array within an object and its elements are again objects. Thereby, you would access the name attribute of the first author like so:

$jsonStr = '{
 "title":   "Archive",
 "authors": [
  {
   "name": "MyName",
   "company":   "Company",
   "email": "emailopping.org",
   "website":   "website"
  }
 ]
}';

$result_content_module = json_decode($jsonStr);
echo $result_content_module->authors[0]->name;

The snippet from above will print the following.

MyName

Live Demo

Beautify your JSON here

Upvotes: 0

Dani
Dani

Reputation: 925

According to your code snippet authors is an array of objects so you have to pass array index

$dt = '{
 "title":   "Archive",
 "authors": [
  {
   "name": "MyName",
   "company":   "Company",
   "email": "emailopping.org",
   "website":   "website"
  }
 ]
}';
$data = json_decode($dt);
echo $data->authors[0]->name;

Now if you have multi dimension array of authors then you have to use loop like following

    foreach($data->authors as $auth){
      echo $auth->name;
   }

Upvotes: 0

Xander
Xander

Reputation: 1696

You have a mixture of objects and arrays.

Specifically, authors is an array so should be accessed using square bracket, rather than arrow, notation. In your example, the array has one entry so you want index 0.

Try:

var_dump($result_content_module->authors[0]->name);

Upvotes: 1

Related Questions