Kardo Kardo - 3 months ago 7
PHP Question

How to implode such an array in PHP?

I want to show a comma separated series of links by the following array using implode:

Array's Name:

$product['product_category']


Array's Data:

Array (
[0] => Array (
[name] => Apparel
[href] => http://localhost/uooro/index.php?route=profile/category&path=12
)
[1] => Array (
[name] => Business Services
[href] => http://localhost/uooro/index.php?route=profile/category&path=15
)
[2] => Array (
[name] => Chemicals
[href] => http://localhost/uooro/index.php?route=profile/category&path=16
)
)


I want to have such a result:

Apparel, Business Services, Chemicals

Answer

PHP 5.5+

You can use array_column if you are running PHP 5.5 or later.

echo implode(', ', array_column($product['product_category'], 'name'));

// Apparel, Business Services, Chemicals

Working example: https://3v4l.org/MsHJb


PHP <5.5

Otherwise, first use array_map to flatten your array, then simply implode.

echo implode(", ", array_map(function($category) {
    return $category['name'];
}, $product['product_category']));

// Apparel, Business Services, Chemicals

Working example: https://3v4l.org/rKJHB