php 内爆数组值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4854520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implode array values?
提问by qwerty
So, i've got an array like this:
所以,我有一个这样的数组:
Array
(
[0] => Array
(
[name] => Something
)
[1] => Array
(
[name] => Something else
)
[2] => Array
(
[name] => Something else....
)
)
Is there a simple way of imploding the values into a string, like this:
是否有一种简单的方法将值内爆为字符串,如下所示:
echo implode(', ', $array[index]['name']) // result: Something, Something else, Something else...
withoutusing a loop to concate the values, like this:
不使用循环来连接值,如下所示:
foreach ($array as $key => $val) {
$string .= ', ' . $val;
}
$string = substr($string, 0, -2); // Needed to cut of the last ', '
回答by Radek Benkel
Simplest way, when you have only one item in inner arrays:
最简单的方法,当内部数组中只有一项时:
$values = array_map('array_pop', $array);
$imploded = implode(',', $values);
回答by Oleg Matei
In PHP 5 >= 5.5.0
在 PHP 5 >= 5.5.0
implode(', ', array_column($array, 'name'))
回答by BoltClock
You can use a common array_map()
trick to "flatten" the multidimensional array then implode()
the "flattened" result, but internally PHP still loops through your array when you call array_map()
.
您可以使用一个常见的array_map()
技巧来“展平”多维数组,然后implode()
是“展平”的结果,但在您调用array_map()
.
function get_name($i) {
return $i['name'];
}
echo implode(', ', array_map('get_name', $array));