0

I hope you can help me with this simple problem in converting arrays of objects to individual objects. So I can directly call their attributes.

What I mean is, I have this data listed below:

array(3) {
  [0]=>
  object(stdClass)#259 (8) {
    ["id"]=>
    int(2)
    ["author_id"]=>
    int(2)
    ["title"]=>
    string(17) "The Emperorasdasd"
    ["publisher"]=>
    string(15) "De publishing"
    ["created_at"]=>
    string(19) "2013-10-11 12:49:00"
    ["updated_at"]=>
    string(19) "2013-10-12 09:44:58"
    ["date_published"]=>
    string(10) "02-12-2013"
    ["name"]=>
    string(8) "John Doe"
  }
  [1]=>
  object(stdClass)#260 (8) {
    ["id"]=>
    int(1)
    ["author_id"]=>
    int(1)
    ["title"]=>
    string(4) "Demo"
    ["publisher"]=>
    string(10) "ooqwwoeqoe"
    ["created_at"]=>
    string(19) "2013-10-12 09:45:31"
    ["updated_at"]=>
    string(19) "2013-10-12 09:45:36"
    ["date_published"]=>
    string(10) "26-12-1993"
    ["name"]=>
    string(11) "Demo"
  }
  [2]=>
  object(stdClass)#261 (8) {
    ["id"]=>
    int(1)
    ["author_id"]=>
    int(1)
    ["title"]=>
    string(12) "Read My Mind"
    ["publisher"]=>
    string(13) "TF Publishing"
    ["created_at"]=>
    string(19) "2013-10-12 09:46:53"
    ["updated_at"]=>
    string(19) "2013-10-12 09:46:53"
    ["date_published"]=>
    string(10) "30-11-2009"
    ["name"]=>
    string(11) "James Mones"
  }
}

How will I convert the 3 item array into 3 individual objects? So I can call them directly like: $books->id, not $books[0]->id ?

0

3 Answers 3

2

Its not 100% clear what you mean, whether you want the three objects as seperate variables or you just need a way of accessing them.

A simple foreach should suffice.

foreach ( $collection as $model ) 
{
    $id = $model->id;
}

alternatively the answer supplied by Eugen would grab specific indexes to variables for you to use.

Sign up to request clarification or add additional context in comments.

Comments

0

Is this, what you mean?

$book0 =& $books[0];
$book1 =& $books[1];
$book2 =& $books[2];

echo $book0->id

Comments

0

You can use

list($books1, $books2, $books3) = $arrayOfObjects;

DEMO.

So, if your $arrayOfObjects has three objects inside it then every objects will be extracted from the array and will be stored in variables supplied in the list and you can use the first object like

echo $books1->id;
echo $books2->id;
echo $books3->id;

Also, using a loop you can do it like

foreach($arrayOfObjects as $books) {
    echo $books->id;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.