0

I'm trying to combine a single-dimensional array with a multi-dimensional array. I see that there is an array_combine function and an array_merge function, but they don't seem to give me the result I need. I have the following arrays:

$days = Array ( 
    [0] => Array ( 
        [0] => 3 
        [1] => 6 
    ) 
    [1] => Array ( 
        [0] => 6 
        [1] => 12 
    ) 
    [2] => Array ( 
        [0] => 2 
        [1] => 4 
    )
)

$names = Array ( 
    [0] => Joe Smith 
    [1] => John Doe 
    [2] => Jack Frost
)

and this is the result I get when using array_merge($days,$names):

$result = Array ( 
    [0] => Array ( 
        [0] => 3 
        [1] => 6 
    ) 
    [1] => Array ( 
        [0] => 6 
        [1] => 12 
    ) 
    [2] => Array ( 
        [0] => 2 
        [1] => 4 
    ) 
    [3] => Joe Smith 
    [4] => John Doe 
    [5] => Jack Frost 
)

How do I get the following result:

$result = Array ( 
    [0] => Array (
        [0] => John Smith
        [1] => Array ( 
            [0] => 3 
            [1] => 6
        )
    ) 
    [1] => Array (
        [0] => John Doe
        [1] => Array ( 
            [0] => 6 
            [1] => 12 
        )
    ) 
    [2] => Array (
        [0] => Jack Frost
        [1] => Array ( 
            [0] => 2 
            [1] => 4 
        )
    )
)

Any ideas? Thanks

2
  • @JonathanM would it be easier to put the value of the single-level array as the key in the multi-level array. For example: 'John Smith' => array(...) Commented Oct 12, 2015 at 20:00
  • that depends on what you want as output. If you change what you want as output, you can always make it "easier". Commented Oct 12, 2015 at 20:02

1 Answer 1

2

Using example #4 from the docs for array_map(), here's a cool way to do it:

$result = array_map(null, $names, $days);
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for. Thanks

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.