phpforeachimplodestdclass

Optimal way to convert stdClass Object array to string


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.


Solution

  • 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));