Home > Software design >  Combine two arrays with multiple values and same keys
Combine two arrays with multiple values and same keys

Time:12-14

I have two arrays with keys and values and i want to combine them:

Array 1

[0]=>string "Width"
[1]=>string "Height"
[2]=>string "Length"
[3]=>string "Width"
[4]=>string "Height"
[5]=>string "Length"

Array 2

[0]=>string "42 cm"
[1]=>string "2 cm"
[2]=>string "210 cm"
[3]=>string "5 cm"
[4]=>string "10 cm"
[5]=>string "15 cm"

With array_combine(array1, array2) output:

[Width]=>string "42 cm"
[Height]=>string "2 cm"
[Length]=>string "210 cm"
[Width]=>string "42 cm"
[Height]=>string "2 cm"
[Length]=>string "210 cm"

How can i get output?:

[Width]=>string "42 cm"
[Height]=>string "2 cm"
[Length]=>string "210 cm"
[Width]=>string "5 cm"
[Height]=>string "10 cm"
[Length]=>string "15 cm"

CodePudding user response:

You can chunk the two arrays and map array_combine over the chunks.

$result = array_map('array_combine', array_chunk($array1, 3), array_chunk($array2, 3));

This will get you a result like this:

[
    {
        "Width": "42 cm",
        "Height": "2 cm",
        "Length": "210 cm"
    },
    {
        "Width": "5 cm",
        "Height": "10 cm",
        "Length": "15 cm"
    }
]

I think that's probably the closest possible solution to what you're trying to get.

Please note that this will only work if the subsets of keys and values are the same size like they are in your example.

  • Related