Search code examples
phplaravelcollectionsassociative-array

How to get attribute from a collection, with multiple objects inside of an array in Laravel?


I have a collection that contains an array with 2 objects in it. I'm trying to get the email attribute, right now there are only 2 objects, but there could be 100 objects, so I'm not sure if I need a loop or if I need to use array_merge, or something. I've attached a screenshot of the data, I'm not showing the attributes, but just know that one of them is email. I'm die/dumping a variable called $tokens.

In the end, it should return a list of emails, for example:

[email protected]
[email protected]
[email protected]

And I need this logic in the controller, not in the view (.blade), because I'm trying to save this data in a csv file, using fputcsv, that's the main objective and idea here. enter image description here


Solution

  • Thank you to @jagcweb for the inspiration, his code/answer just needed a couple of tweaks. The following works and does what I was trying to do:

    $emails_array = array();
    for($i=0; $i <= sizeof($tokens)-1; $i++) {
        array_push($emails_array, $tokens[$i]["email"]);
    }
    

    Now the $emails_array contains an array with both emails in it.