VishnuPrasad
VishnuPrasad

Reputation: 1078

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.

Upvotes: 0

Views: 1156

Answers (3)

iateadonut
iateadonut

Reputation: 2239

json_encode($object) will turn it into a JSON string

Upvotes: 1

php-dev
php-dev

Reputation: 7156

Use array_map function

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

Hope it helps

Upvotes: 1

Alma Do
Alma Do

Reputation: 37365

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

Upvotes: 2

Related Questions