Using implode for stdClass Objects in php

foreach($categories as $category) { print_r($category); } 

The above code gives me the following result.

 stdClass Object ( [category_Id] => 4 [category_Title] => cat 4 ) stdClass Object ( [category_Id] => 7 [category_Title] => cat 7 ) stdClass Object ( [category_Id] => 6 [category_Title] => cat 6 ) 

how can i use implode(', ' ) to get the following result:

cat 4, cat 7, cat 6

I used it but got an error

+7
php implode
source share
3 answers

Try

 foreach($categories as $category) { $new_arr[] = $category->category_Title; } $res_arr = implode(',',$new_arr); print_r($res_arr); 
+2
source share

You can easily do this simply by using an array. Most people seem to have missed the college or C program.

 implode(',',(array) $categories); 

check this topic if in doubt me Convert PHP object to associative array

+13
source share

Here's an alternative solution using array_map :

 $str = implode(', ', array_map(function($c) { return $c->category_Title; }, $categories)); 
+11
source share

All Articles