-2

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"
1
  • 2
    You can't because array keys must be unique. You would have to use a different structure. [['width' => '42 cm', 'height' => '2 cm'], [...], [...]] for example Commented Dec 13, 2021 at 19:05

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.