简体   繁体   English

打印出类型对象的PHP数组

[英]Printing out a PHP Array of type object

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: 我需要做的是打印出用户ID的逗号分隔,这样:

10, 16, 27, 79 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 我猜它是在for循环中,但我正在寻找在PHP中最有效的方法

Oh and the Array name is: $mArray 哦,数组名称是:$ 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. 致命错误:不能使用stdClass类型的对象作为数组。

I think it's because this array is not a typical array so it requires some different syntax? 我认为这是因为这个数组不是典型的数组所以它需要一些不同的语法?

Each array element is a (anonymous) object and user_id is a property. 每个数组元素都是(匿名)对象, user_id是属性。 Use the object property access syntax ( -> ) to access it: 使用object属性访问语法( -> )来访问它:

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

you can do it this way since you are working with objects 你可以这样做,因为你正在使用对象

Use this if you want to avoid the trailing comma ( , ). 如果要避免使用尾随逗号( ,,请使用此选项。

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

echo join(', ', $ids);

Pretty close... 八九不离十...

foreach($mArrray as $k => $cur)
{
  echo $cur->user_id.', ';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM