打印出一个对象类型的 PHP 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5924106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing out a PHP Array of type object
提问by Jordash
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?
我认为这是因为这个数组不是典型的数组,所以它需要一些不同的语法?
回答by alexn
Each array element is a (anonymous) object and user_id
is a property. Use the object property access syntax (->
) to access it:
每个数组元素都是一个(匿名)对象并且user_id
是一个属性。使用对象属性访问语法 ( ->
) 来访问它:
foreach($mArray as $k => $cur)
{
echo $cur->user_id;
echo ',';
}
回答by Ibu
foreach ($mArray as $cur){
echo $cur->user_id;
}
you can do it this way since you are working with objects
您可以这样做,因为您正在处理对象
回答by Philippe Gerber
Use this if you want to avoid the trailing comma (,
).
如果您想避免尾随逗号 ( ,
),请使用此选项。
$ids = array();
foreach ($array as $obj){
$ids[] = $obj->user_id;
}
echo join(', ', $ids);
回答by csi
Pretty close...
很接近了...
foreach($mArrray as $k => $cur)
{
echo $cur->user_id.', ';
}