Home > Software engineering >  construct PHP multidimensional array from Laravel object
construct PHP multidimensional array from Laravel object

Time:02-17

This is an example of a data list from Laravel DB:

Illuminate\Support\Collection Object
(
[items:protected] => Array
    (
        [0] => stdClass Object
            (
                [category] => Protections menstruelles
                [sub_category] => Sous-vêtements lavables
                [model] => Culotte menstruelle
            )

        [1] => stdClass Object
            (
                [category] => T-shirt, Top & Polo
                [sub_category] => Débardeur, Caraco
                [model] => Bustier
            )

        [2] => stdClass Object
            (
                [category] => Protections menstruelles
                [sub_category] => Sous-vêtements lavables
                [model] => Tanga menstruel
            )

        [3] => stdClass Object
            (
                [category] => Protections menstruelles
                [sub_category] => Sous-vêtements lavables
                [model] => Body menstruel
            )

        [4] => stdClass Object
            (
                [category] => Protections menstruelles
                [sub_category] => Maillot de bain menstruel
                [model] => 1 pièce
            )

        [5] => stdClass Object
            (
                [category] => Homewear
                [sub_category] => Chaussettes
                [model] => Socquettes
            )

        [6] => stdClass Object
            (
                [category] => Plage
                [sub_category] => Bas de maillot
                [model] => Short de bain
            )

        [7] => stdClass Object
            (
                [category] => Lingerie & Sous-vêtement
                [sub_category] => Soutien-gorge
                [model] => Triangle
            )

        [8] => stdClass Object
            (
                [category] => Lingerie & Sous-vêtement
                [sub_category] => Culotte, tanga & string
                [model] => Tanga
            )

        [9] => stdClass Object
            (
                [category] => Lingerie & Sous-vêtement
                [sub_category] => Culotte, tanga & string
                [model] => Culotte
            )

    )
)

And I would like to create a JSON object which could be like that:

        var subjectObject = {
          "Protections menstruelles": {
            "Maillot de bain menstruel": ["1 pièce"],
            "Sous-vêtements lavables": ["Body menstruel"]
          },
          "Lingerie & Sous-vêtement": {
            "Soutien-gorge": ["Triangle"],
            "Culotte, tanga & string": ["Tanga", "Culotte"]
          }
          ...
        }

The idea is to ask some questions in select and with JavaScript conditional the options according previous select. I want to use this tutorial for that: https://www.w3schools.com/howto/howto_js_cascading_dropdown.asp I need a help to construct the json input.

It's working with this laravel DB request :

->select('category','sub_category','model')
->whereNotNull('category')
->whereNotNull('sub_category')
->whereNotNull('model')
->distinct()
->get()
->groupBy('category')
->map(function($item){
    return collect($item)
        ->groupBy('sub_category')
        ->map(function($item){
            return collect($item)->pluck('model');
        })->toArray();
      })->toJson();

But i Can't use it in javascript :

var subjectObject = "{{ $collection }}";

It's not a json like in the example :

var subjectObject = {
 "Front-end": {
  "HTML": ["Links", "Images", "Tables", "Lists"],
  "CSS": ["Borders", "Margins", "Backgrounds", "Float"],
  "JavaScript": ["Variables", "Operators", "Functions", "Conditions"]    
 },
 "Back-end": {
   "PHP": ["Variables", "Strings", "Arrays"],
   "SQL": ["SELECT", "UPDATE", "DELETE"]
 }
}

CodePudding user response:

It's a collection. You can use these methods :

  • groupBy method groups the collection's items by a given key
  • map method iterates through the collection and passes each value to the given callback
  • pluck method retrieves all of the values for a given key, and
  • toJson method converts the collection into a JSON serialized string
$collection
    ->groupBy('category')
    ->map(function($item){
        return collect($item)
            ->groupBy('sub_category')
            ->map(function($item){
                return collect($item)->pluck('model');
            })
            ->toArray();
    })
    ->toJson();

Output :

{
  "Protections menstruelles": {
    "Sous-vêtements lavables": [
      "Culotte menstruelle",
      "Tanga menstruel",
      "Body menstruel"
    ],
    "Maillot de bain menstruel": [
      "1 pièce"
    ]
  },
  "T-shirt, Top & Polo": {
    "Débardeur, Caraco": [
      "Bustier"
    ]
  },
  "Homewear": {
    "Chaussettes": [
      "Socquettes"
    ]
  },
  "Plage": {
    "Bas de maillot": [
      "Short de bain"
    ]
  },
  "Lingerie & Sous-vêtement": {
    "Soutien-gorge": [
      "Triangle"
    ],
    "Culotte, tanga & string": [
      "Tanga",
      "Culotte"
    ]
  }
}
  • Related