array:5 [
0 => array:1 [
"location_id" => 1
]
1 => array:1 [
"location_id" => 4
]
2 => array:1 [
"location_id" => 6
]
3 => array:1 [
"location_id" => 7
]
4 => array:1 [
"location_id" => 8
]
]
convert this into ["1","4","6","7","8",]
as used this ["1","4","6","7","8",]array in different query
CodePudding user response:
You can use Laravel Collection pluck
method to only return property which you want from each array item, and after that flatten the result array with flatten
$data = [
[
"location_id" => 1
],
[
"location_id" => 4
],
[
"location_id" => 6
],
[
"location_id" => 7
],
[
"location_id" => 8
]
];
$result = collect($data)->pluck('location_id')->flatten();
CodePudding user response:
Welcome to Stackoverflow.
You can use the laravel helper array flatten method: Read more about it from here: https://laravel.com/docs/9.x/helpers#method-array-flatten
// Add the helper class call in the controller header
use Illuminate\Support\Arr;
// The actual array
$array = [
0 => [
"location_id" => 1
],
1 => [
"location_id" => 4
],
2 => [
"location_id" => 6
],
3 => [
"location_id" => 7
],
4 => [
"location_id" => 8
]
];
// Flatten the array function
$result = Arr::flatten($array);
Results:
['1','4','6','7','8']
CodePudding user response:
Not as clean you might want but get the job done:
$resultSet = collect($data)->map(function($item){
return $item['location_id'];
})->toArray();
$resultString = "[";
foreach($resultSet as $item){
$resultString .= "'{$item}'" . ",";
}
$resultString = rtrim($resultString, ","); // produces this: "['1','4','6','7','8']"
$resultString .= "]";
dd($resultString);
CodePudding user response:
You can use the laravel helper array pluck method Read more about it from here: https://laravel.com/docs/9.x/helpers#method-array-pluck
$data = \Arr::pluck($array, 'location_id');
$result = array_map('strrev', $data);
// ["1","4","6","7","8"]