Home > Mobile >  get a two dimensional array out of a query sql
get a two dimensional array out of a query sql

Time:03-04

i have a query like that:

$pd= DB::table("projects")
            ->orderBy("project_number", "asc")
            ->select('name' , "type")
            ->get()->keyBy('date_scheduled');;

and i get a array keyed By the date_scheduled which is fine, but the problem is date_scheduled is not unique so it overwrites the entries. So i need to get a two dimensional array with keyby date_scheduled like:

[
 'date_1_of_date_scheduled' => [0 => '1', 1 => '4', 2 => '17']
 'date_2_of_date_scheduled' => [0 => '15', 1 => '64', 2 => '1142']
 'date_3_of_date_scheduled' => [0 => '25', 1 => '125', 2 => '66']
]

CodePudding user response:

You can use groupBy() instead of keyBy(): https://laravel.com/docs/8.x/collections#method-groupby

$pd = DB::table("projects")
    ->orderBy("project_number", "asc")
    ->select('name' , "type")
    ->get()
    ->groupBy('date_scheduled');

CodePudding user response:

You can use the laravel map function for the purpose

Try that:

$pd= DB::table("projects")
            ->orderBy("project_number", "asc")
            ->select('name' , "type")
            ->get()
            ->map(function ($item) {
               return ['date_'.$item->date_scheduled.'_of_date_scheduled' => $item->YOUR_DESIRED_DATA] ;
             }
  • Related