php Laravel 数组到字符串的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36134258/
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
Laravel array to string conversion
提问by Beffing
I want to convert my array to comma separated string.
我想将我的数组转换为逗号分隔的字符串。
my array
我的数组
array:2 [
0 => array:1 [
"name" => "streaming"
]
1 => array:1 [
"name" => "ladies bag"
]
]
I want result as streaming,ladies bag
我想要结果 streaming,ladies bag
回答by Joel Hinz
Since these look like Laravel collections converted to arrays, I would suggest using the inbuilt implode()
method.
由于这些看起来像转换为数组的 Laravel 集合,我建议使用内置implode()
方法。
As per the docs:
根据文档:
$collection = collect([
['account_id' => 1, 'product' => 'Desk'],
['account_id' => 2, 'product' => 'Chair'],
]);
$collection->implode('product', ', ');
// Desk, Chair
Reference: https://laravel.com/docs/master/collections#method-implode
参考:https: //laravel.com/docs/master/collections#method-implode
However, if they're ordinary arrays, and since it's not a single array, you'd have to write a foreach or flatten it with array_column()
before running PHP's ordinary implode()
function.
但是,如果它们是普通数组,并且由于它不是单个数组,则必须array_column()
在运行 PHP 的普通implode()
函数之前编写 foreach 或将其展平。
回答by Raul H
U could try a simple foreach and add a comma value after every iteration.
你可以尝试一个简单的 foreach 并在每次迭代后添加一个逗号值。
$string='';
foreach ($your_array as $value){
$string .= $value.',';
}
回答by Nishant Sharma
Use a foreach
loop twice to segregate the array and use substr
to remove the last character
使用foreach
循环两次来隔离数组并用于substr
删除最后一个字符
$string = '';
foreach($your_array as $a)
{
foreach($a as $b=>$c)
{
$string .= $c.',';
}
}
$solution = substr($string,0,-1);
print_r($solution);