Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine two arrays with multiple values and same keys

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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"

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading