Displaying keys and values in a multidimensional Laravel object

  collections, laravel, php

I would like to put my keys and values in a collection like this

$attributes = [
            ['key' => 'color', 'value' => 'red'],
            ['key' => 'color', 'value' => 'blue'],
            ['key' => 'color', 'value' => 'red'],
            ['key' => 'height', 'value' => (int) 2],
            ['key' => 'height', 'value' => (int) 2],
            ['key' => 'height', 'value' => (int) 3],
            ['key' => 'height', 'value' => (int) 3],
            ['key' => 'height', 'value' => (int) 3],
            ['key' => 'height', 'value' => (int) 3],
            ['key' => 'height', 'value' => (int) 3],
            ['key' => 'color', 'value' => 'red'],
            ['key' => 'material', 'value' => 'iron'],
            ['key' => 'material', 'value' => 'iron'],
            ['key' => 'material', 'value' => 'gold'],
            ['key' => 'material', 'value' => 'gold'],
            ['key' => 'material', 'value' => 'gold'],
        ];

I also have the values I receive in the database, saved in a json
Like this

 "attributes" => "{"Attribute":[{"Attribute_name":"heigth","Attribute_value":"8"},{"Attribute_name":"color","Attribute_value":"red"},{"Attribute_name":"heigth","Attribute_value":"8"},{"Attribute_name":"heigth","Attribute_value":"2"}]}"

I tried to make something like this

$attributes = [];

        foreach ($feeds as $feed) {
            array_push($attributes, $feed->attributes);
        }
        $test = collect(json_decode($attributes[0]));
        dd($test);

But I will receive something this way

IlluminateSupportCollection {#696
  #items: array:1 [
    "Attribute" => array:4 [
      0 => {#380
        +"Attribute_name": "height"
        +"Attribute_value": "8"
      }
      1 => {#373
        +"Attribute_name": "color"
        +"Attribute_value": "red"
      }
      2 => {#359
        +"Attribute_name": "height"
        +"Attribute_value": "8"
      }
      3 => {#1315
        +"Attribute_name": "height"
        +"Attribute_value": "2"
      }
    ]
  ]

In the end, I would like to somehow push that collection and have the key, value as I have above
Is something like that possible?

Source: Laravel

Leave a Reply