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

The code above 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 I got an error

Afshin
  • 2,337
  • 5
  • 34
  • 54

3 Answers3

26

You may easily do this just casting as an array. Most people seem to have skipped college or C programming.

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

check this thread if you doubt me Convert PHP object to associative array

Community
  • 1
  • 1
Magus
  • 2,589
  • 26
  • 32
21

Here's an alternative solution using array_map:

$str = implode(', ', array_map(function($c) {
    return $c->category_Title;
}, $categories));
Guilherme Sehn
  • 6,498
  • 16
  • 35
  • Nice solution! Thanks. –  Apr 28 '15 at 16:06
  • 2
    @Magus you misunderstood the question. If you read carefully, `$categories` is *already* an array containing three `stdClass` elements which have two properties: `category_Id` and `category_Title`. He asked how to generate a new array of category titles (strings). Just casting `$categories` to an array wouldn't work. – Guilherme Sehn Jul 18 '16 at 13:37
  • 1
    @GuilhermeSehn indeed. I apologize. – Magus Jul 18 '16 at 21:12
  • @GuilhermeSehn very elegant solution! – Phil Young Jul 20 '16 at 12:41
  • this was exactly what I was looking for! you read my mind! thank you! – rome3ro Mar 26 '20 at 06:10
6

Try like

foreach($categories as $category)
{
    $new_arr[] = $category->category_Title;
}
$res_arr = implode(',',$new_arr);
print_r($res_arr);
Gautam3164
  • 28,027
  • 10
  • 58
  • 83