hellilyntax
hellilyntax

Reputation: 197

Iterating through Laravel 4 custom collection

I have created my own collection in Laravel 4. Below is the code,

    $family = Collection::make([
        ['name' => 'Mom', 'age' => 30],
        ['name' => 'Dad', 'age' => 31]
    ]);

    foreach ($family as $member) {
        echo $member->name;
        echo "<br>";
    }
    return;

The problem is, i cannot call 'name' or 'age' while iterating the loop. Is there something wrong with the collection?

Upvotes: 1

Views: 172

Answers (2)

aldrin27
aldrin27

Reputation: 3407

You have array of array's so that you can access that using $member['name']

For example:

If you have array of arrays

 Array
 (
  [0] => Array
    (
        [name] => Mom
        [age] => 30
    )
  [1] => Array
    (
        [name] => Dad
        [age] => 31
    )
 )

You can access that using below:

 foreach($family as $key => $member)
{
    echo $member['name'];
}

If you have object of arrays you can access that using $member->name

Example of array of objects:

Array
 (
  [0] => stdClass Object
    (
        [name] => Mom
        [age] => 30
    )
  [1] => stdClass Object
    (
        [name] => Dad
        [age] => 31
    )
)

You can access that using below:

 foreach ($family as $key => $member) 
 {
    echo $member->name;
 }

NOTE: To test or to see the resulted values use print_r($result) OR var_dump($result)

Upvotes: 1

Felix Bernhard
Felix Bernhard

Reputation: 415

This is a pure php solution:

$family = [
    ['name' => 'Mom', 'age' => 30],
    ['name' => 'Dad', 'age' => 31]
];

foreach ($family as $k=>$v) {
    echo $v["name"];
    echo "<br>";
}
return;

(I don't know "Laravel 4" sorry, but this should work)

Upvotes: 0

Related Questions