如何在PHP中内爆这样的数组?

时间:2016-06-09 15:15:39

标签: php arrays implode

我想使用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 

4 个答案:

答案 0 :(得分:7)

PHP 5.5 +

如果您运行的是PHP 5.5或更高版本,则可以使用array_column

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

// Apparel, Business Services, Chemicals

工作示例:https://3v4l.org/MsHJb

PHP< 5.5

否则,首先使用array_map展平你的数组,然后简单地内爆。

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

// Apparel, Business Services, Chemicals

工作示例:https://3v4l.org/rKJHB

答案 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'));

从本页获取的信息:

Implode data from a multi-dimensional array

答案 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);