I am retrieving data from mysql database by help of modal in controller. As there is query which will run many times and I have to store all retrieval data into one array. I need to store data data in following mentioned format while it is not happening.
Controller code
class subcontroller extends Controller
{
public function Index(Request $req)
{
$arr=$req->get('myArray');
$data=[];
foreach($arr as $item){
$entry=item::where('jobtype',$item)->get();
array_push($data, $entry);
}
return $data;
}
}
Output
[[{"jobname":"Electrician","jobtype":"Electrical Wiring"}],[{"jobname":"Electrician","jobtype":"Electrical Work"}]]
Desire Result should be like:
[{"jobname":"Electrician","jobtype":"Electrical Wiring"},{"jobname":"Electrician","jobtype":"Electrical Work"}]
My Answer:
To achieve the desired result, you can use the `push` method instead of `array_push` and then flatten the array using the `flatten` method. Here's the updated code:
php
class subcontroller extends Controller
{
public function Index(Request $req)
{
$arr = $req->get('myArray');
$data = [];
foreach ($arr as $item) {
$entry = item::where('jobtype', $item)->get();
$data->push($entry);
}
$flattenedData = $data->flatten();
return $flattenedData;
}
}
By using the `push` method on the `$data` collection, you will add each retrieved data as a separate item in the collection. Then, by using the `flatten` method on the collection, you will flatten the array and get the desired result.
Rate this post
5 of 5 based on 1301 votesComments