将stdClass Object数组转换为字符串
的最佳方法我的stdClass对象格式是:
$autoArea = Array (
[0] => stdClass Object ( [area] => aarea )
[1] => stdClass Object ( [area] => area )
[2] => stdClass Object ( [area] => barea )
[3] => stdClass Object ( [area] => carea )
)
我需要输出字符串:
'aarea', 'area', 'barea', 'carea'
我在2下面尝试过:
$areas="";
foreach($autoArea as $ar)
{
if($areas=="")
{
$areas="'".$ar->area."'";
}
else
{
$areas=$areas.","."'".$ar->area."'";
}
}
echo $areas;
和
$tp= array();
foreach($autoArea as $ar)
{
$tp[] = $ar->area;
}
$areas=implode("','", $tp);
$areas="'".$areas."'";
echo $areas;
哪一个更优化,或者任何其他建议我。
答案 0 :(得分:2)
只需提取所需的属性,例如:
$data = [
(object)['area' => 'foo'],
(object)['area' => 'bar'],
(object)['area' => 'baz']
];
$result = join(',', array_map(function($x)
{
return $x->area;
}, $data));
答案 1 :(得分:1)
使用array_map功能
echo implode(', ', array_map(function($item) {return $item->area;}, $autoArea));
希望有所帮助