Creating Array of Objects using stdClass

Click HERE for the original code.

// CREATE FIRST AN ARRAY WHERE IN THE OBJECTS WILL BE STORED
$lib = array();
$book = new stdClass;

$book->title = "Harry Potter and the Prisoner of Azkaban";
$book->author = "J. K. Rowling";
$book->publisher = "Arthur A. Levine Books";
$book->amazon_link = "http://www.amazon.com/dp/0439136369/";
// STORE THE OBJECTS IN THE ARRAY
$lib[] = $book;

$book = new stdClass;
$book->title = "Pugad Baboy";
$book->author = "Pol Medina";
$book->publisher = "Advil Publishing House";
$book->amazon_link = "http://www.amazon.com/dp/0439136369/";
// STORE THE OBJECTS IN THE ARRAY
$lib[] = $book;

foreach($lib as $key=>$libs)
{
echo $libs->title;
}

in the given code above, the objects can be printed via dash and arrow -> instead of an array [”]

but you can also do this by using arrays alone.


$lib= array('0' => array("title" => 'Harry Potter and the Prisoner of Azkaban',
"author" => 'J. K. Rowling'),
'1' => array("title" => 'Pugad Baboy',
"author" => 'Pol Medina'),);

foreach($lib as $key=>$libs)
{
echo $libs['title'];
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s