Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out a PHP Array of type object

Tags:

arrays

php

I have an array that looks like this:

Array
(
    [0] => stdClass Object
        (
            [user_id] => 10
            [date_modified] => 2010-07-25 01:51:48
        )

    [1] => stdClass Object
        (
            [user_id] => 16
            [date_modified] => 2010-07-26 14:37:24
        )

    [2] => stdClass Object
        (
            [user_id] => 27
            [date_modified] => 2010-07-26 16:49:17
        )

    [3] => stdClass Object
        (
            [user_id] => 79
            [date_modified] => 2010-08-08 18:53:20
        )

)

and what I need to do is print out the user id's comma seperated so:

10, 16, 27, 79

I'm guessing it'd be in a for loop but i'm looking for the most efficient way to do it in PHP

Oh and the Array name is: $mArray

I've tried this:

foreach($mArray as $k => $cur)
{
    echo $cur['user_id'];
    echo ',';
}

which others have suggested.

However I keep getting this error:

Fatal error: Cannot use object of type stdClass as array in.

I think it's because this array is not a typical array so it requires some different syntax?

like image 820
Jordash Avatar asked May 07 '11 21:05

Jordash


4 Answers

Each array element is a (anonymous) object and user_id is a property. Use the object property access syntax (->) to access it:

foreach($mArray as $k => $cur)
{
    echo $cur->user_id;
    echo ',';
}
like image 111
alexn Avatar answered Sep 29 '22 09:09

alexn


foreach ($mArray as $cur){
   echo $cur->user_id;
}

you can do it this way since you are working with objects

like image 29
Ibu Avatar answered Sep 29 '22 07:09

Ibu


Use this if you want to avoid the trailing comma (,).

$ids = array();
foreach ($array as $obj){
    $ids[] = $obj->user_id;
}

echo join(', ', $ids);
like image 45
Philippe Gerber Avatar answered Sep 29 '22 07:09

Philippe Gerber


Pretty close...

foreach($mArrray as $k => $cur)
{
  echo $cur->user_id.', ';
}
like image 23
csi Avatar answered Sep 29 '22 08:09

csi