Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

qTylok's avatar

Push data from a array to a collection with key and value

Hi, I'm back with a question about how I could push data from an array into a collection of keys and values I have this collection

#items: array:6 [
    0 => array:8 [
      "condition" => "used"
      "brand" => "LG"
      "gender" => ""
      "age_group" => ""
      "color" => ""
      "size" => ""
      "shipping" => "US::Standard:14.95 USD"
      "shipping_weight" => "9.2 lbs"
    ]
    1 => array:8 [
      "condition" => "new"
      "brand" => "BBC"
      "gender" => ""
      "age_group" => ""
      "color" => ""
      "size" => ""
      "shipping" => "US::Express:3.80 USD"
      "shipping_weight" => ""
    ]

And I would like the value on the left to be a key and the value on the right a value So I try to collect the data but in the end I only have a worthless key what idea do you have to put all that data in a key value like he wants me to do below?

$finalCollection = new Collection();

        foreach ($attributesCollection as $attributeCollection) {
            foreach ($attributeCollection as $key => $value) {
                $finalCollection = collect(['key' => $key, 'value' => $value]);
            }
        }
0 likes
8 replies
Sinnbeck's avatar

Can you show an example of how you would expect the outout to look?

qTylok's avatar

@Sinnbeck for example

['key' => 'condition', 'value' => 'used']
['key'= >'brand', 'value'= >LG] ...

and so on

SilenceBringer's avatar

@qtylok

collect($attributesCollection)
	->map(fn ($attribute) => // for each attribute
		collect($attribute)
			->map(fn ($value, $key) => [ //wrap every key-value pair into array
				'key' => $key,
				'value' => $value
			])
			->values() // remove keys
	)
SilenceBringer's avatar

@qtylok

collect($attributesCollection)
	->map(fn ($value, $key) => [
		'key' => $key,
		'value' => $value
	])
Snapey's avatar

but that is how your data is now.....

in each item you have an array of key, value pairs

qTylok's avatar

@Snapey I would like to put them all in a collection where I have the above example "key" and "value"

Snapey's avatar

you cannot, you have repeated keys, so you will get an array of arrays, as you have now

jlrdw's avatar

The format it is already in:

#items: array:6 [
    0 => array:8 [
      "condition" => "used"
      "brand" => "LG"
      "gender" => ""
      "age_group" => ""
      "color" => ""
      "size" => ""
      "shipping" => "US::Standard:14.95 USD"
      "shipping_weight" => "9.2 lbs"
    ]
    1 => array:8 [
      "condition" => "new"
      "brand" => "BBC"
      "gender" => ""
      "age_group" => ""
      "color" => ""
      "size" => ""
      "shipping" => "US::Express:3.80 USD"
      "shipping_weight" => ""
    ]
    .. more

Is already the easiest way to work with that data. Just suggestion.

Please or to participate in this conversation.