13
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,427
  • 5
  • 36
  • 56

3 Answers3

27

You can cast the object as an array.

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

For more information: Convert a PHP object to an associative array

Magus
  • 2,905
  • 28
  • 36
  • 1
    it works for array but not for object as OP requested – casusbelli Oct 13 '17 at 16:42
  • You can indeed cast an object to array, but casting `$categories` and imploding the result does not make any sense. This answer is seemingly trying to concatenate the properties of a single object, as in `implode(',', (array)$category)`, but that would produce `'4,cat 4'`. – Álvaro González May 03 '23 at 12:08
24

Here's an alternative solution using array_map:

$str = implode(', ', array_map(function($c) {
    return $c->category_Title;
}, $categories));
Guilherme Sehn
  • 6,727
  • 18
  • 35
  • 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
7

Try like

foreach($categories as $category)
{
    $new_arr[] = $category->category_Title;
}
$res_arr = implode(',',$new_arr);
print_r($res_arr);
GautamD31
  • 28,552
  • 10
  • 64
  • 85