Array of hashes laravel

607 Views Asked by At

Using Laravel 4.2 Have the below datastructure retrieved by using Eloquent queries.

[
  {
      Id: 1,
      Product:Test1,
      TypeId:100
   }
     {
      Id: 2,
      Product:Test2,
      TypeId:200
   }
      {
      Id: 3,
      Product:Test2,
      TypeId:200
   }
];

Want to create a hash map based on TypeId as key so I can search the products easily. Want the final output below way

{
      '100' :  {
          Id: 1,
          Product:Test1,
          TypeId:100
       },
       '200' : [

                     {
          Id: 2,
          Product:Test2,
          TypeId:200
       },
          {
          Id: 3,
          Product:Test2,
          TypeId:200
       }


       ]
}

Tried the below eloquent function but duplicates in the Type Id 200 are ignored.
$type_id_hash=$fm->fmmodelitems->keyBy('TypeId');

For typeid 200 only one record exists when using keyby function as it ignore duplicates. I want to search array of hashmap for a key like typeid. How can it be done.

1

There are 1 best solutions below

1
On BEST ANSWER

Perhaps you want groupBy on Collection:

$grouped = $fm->fmmodelitems->groupBy('TypeId');

This should group them under that 'key'.

$collection = new Illuminate\Support\Collection([
    ['Id' => 1, 'Product' => 'Test1', 'TypeId' => 100],
    ['Id' => 2, 'Product' => 'Test2', 'TypeId' => 200],
    ['Id' => 3, 'Product' => 'Test3', 'TypeId' => 200]
]);

$grouped = $collection->groupBy('TypeId');

$grouped->all();

// array(
//   100 => array(
//     0 => array(
//       'Id' => 1,
//       'Product' => 'Test1',
//       'TypeId' => 100
//     )
//   ),
//   200 => array(
//     0 => array(
//       'Id' => 2,
//       'Product' => 'Test2',
//       'TypeId' => 200
//     ),
//     1 => array(
//       'Id' => 3,
//       'Product' => 'Test3',
//       'TypeId' => 200
//     )
//   )
// )