문제

Optimal way to convert stdClass Object array to string

my stdClass object format is:

$autoArea = Array (
    [0] => stdClass Object ( [area] => aarea )
    [1] => stdClass Object ( [area] => area )
    [2] => stdClass Object ( [area] => barea ) 
    [3] => stdClass Object ( [area] => carea )
)

i need out put as string:

'aarea', 'area', 'barea', 'carea'

i tried below 2:

$areas="";
foreach($autoArea as $ar)
{
    if($areas=="")
    {
        $areas="'".$ar->area."'";
    }
    else
    {
        $areas=$areas.","."'".$ar->area."'";
    }
}
echo $areas; 

and

$tp= array();
foreach($autoArea as $ar)
{
    $tp[] = $ar->area;
}

$areas=implode("','", $tp); 
$areas="'".$areas."'";
echo $areas; 

Which one is more optimal, or any other suggest me.

도움이 되었습니까?

해결책

Just extract desired property, like:

$data = [
   (object)['area' => 'foo'],
   (object)['area' => 'bar'],
   (object)['area' => 'baz']
];
$result = join(',', array_map(function($x)
{
   return $x->area;
}, $data));

다른 팁

Use array_map function

echo implode(', ', array_map(function($item) {return $item->area;}, $autoArea));

Hope it helps

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top