I have input in view laravel like below add more functionality.
<input type="text" name="batch_numbers[1]numbers">
I have variable of array. Want to make that array to string using comma seperator.
$variable = array:[
0 => array:1 [
"numbers" => "TS-001-0005"
]
1 => array:1 [
"numbers" => "TS-001-0006"
]
2 => array:1 [
"numbers" => "TS-001-0007"
]
3 => array:1 [
"numbers" => "TS-001-0008"
]
4 => array:1 [
"numbers" => "TS-001-0009"
]
]
Need to do this array in below format. tring using implode function but
TS-001-0005,TS-001-0006,TS-001-0007,TS-001-0008,TS-001-0009
If anyone have idea how to do this please let me know.
CodePudding user response:
So, in your last question, you attempted to use PHP
's implode()
function. This is fine, but doesn't work well on nested arrays. In your case, you don't need a nested Array:
<input type="text" name="batch_numbers[0]"/>
<input type="text" name="batch_numbers[1]"/>
<input type="text" name="batch_numbers[2]"/>
Given those inputs, to get a CSV of their values, you can simply use:
$csv = implode(',', $request->input('batch_numbers'));
Proper nested inputs would be:
<input type="text" name="batch_numbers[0]['numbers']"/>
<input type="text" name="batch_numbers[1]['numbers']"/>
<input type="text" name="batch_numbers[2]['numbers']"/>
To implode()
this, you'd need a different method, maybe something like:
$csv = implode(',', array_column($request->input('batch_numbers'), 'numbers')));
CodePudding user response:
You can simply achieve using the flatten and the join methods provided by Laravel framework, this way:
Import:
use Illuminate\Support\Arr;
Then:
Arr::join(Arr::flatten($variable), ',')
Explanation:
Arr::flatten
will return a new single level array from multi level array by removing all the keys except values. While, Arr::join
will return a string, joining all the array elements/values separated by a comma ,
.
Output:
TS-001-0005,TS-001-0006,TS-001-0007,TS-001-0008,TS-001-0009