简体   繁体   English

Laravel 数组到字符串的转换

[英]Laravel array to string conversion

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

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.但是,如果它们是普通数组,并且由于它不是单个数组,则在运行 PHP 的普通implode()函数之前,您必须编写 foreach 或使用array_column()将其展平。

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

U could try a simple foreach and add a comma value after every iteration.你可以尝试一个简单的 foreach 并在每次迭代后添加一个逗号值。

 $string='';
 foreach ($your_array as $value){
    $string .=  $value.',';
 }

也许像那样简单一点

$string=implode(",",$your_array);

I have tried the following code to convert array to string in laravel blade file and it works fine .我已尝试使用以下代码将数组转换为 laravel 刀片文件中的字符串,并且工作正常。

<body>
  <center>
     <h1> LARAVEL ARRAY TO STRING CONVERSION </h1>
  </center>
  <div class="main">
     <?php
        $arr=array("this","is","an","array");
        
        echo "array elements are"."<br>";
        
        foreach($arr as $value)
         echo $value."<br>";
        
        echo "The string is "."<br>";
        ?>
     @foreach($arr as $value)
     {!! $value !!}
     @endforeach
  </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM