我想使用implode通过以下数组显示逗号分隔的一系列链接:
数组的名称:
$product['product_category']
数组的数据:
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
)
)
我想得到这样的结果:
Apparel, Business Services, Chemicals
答案 0 :(得分:7)
如果您运行的是PHP 5.5或更高版本,则可以使用array_column
。
echo implode(', ', array_column($product['product_category'], 'name'));
// Apparel, Business Services, Chemicals
否则,首先使用array_map
展平你的数组,然后简单地内爆。
echo implode(", ", array_map(function($category) {
return $category['name'];
}, $product['product_category']));
// Apparel, Business Services, Chemicals
答案 1 :(得分:2)
$output = implode(', ', array_map(function ($names) {
return $names['name'];
}, $product['product_category']));
或在php 5.5.0中:
$output = implode(', ', array_column($product['product_category'], 'name'));
从本页获取的信息:
答案 2 :(得分:1)
$namearray = array_column($product['product_category'],'name');
$namearray = implode(",",$namearray);
我尝试了它并且它正在工作。
答案 3 :(得分:1)
您只需使用foreach
循环即可完成此操作。
<?php
$arr = array(
array('name' => 'Apparel', 'href' => 'http://localhost/uooro/index.php?route=profile/category&path=12'),
array ( 'name' => 'Business Services', 'href' => 'http://localhost/uooro/index.php?route=profile/category&path=15' ),
array ( 'name' => 'Chemicals', 'href' => 'http://localhost/uooro/index.php?route=profile/category&path=16')
);
foreach($arr as $val){
$newArr[] = $val['name'];
};
echo implode(', ',$newArr);