0

I'm trying to manipulate an associative multidimensional array. I've extracted the keys from an array that I want to apply to another's values . . .

These are the keys that I've extracted in another function

$keys = array (
    "id" => "id",
    "addr_street_num" => "addr_street_num",
    "addr_street" => "addr_street",
    "price" => "price",
    "days" =>"days",
    "state" => Array
        (
            "id" => "id",
            "name" => "name"
        ),

    "city" => Array
        (
            "id" => "id",
            "web_id" => "web_id",
            "name" => "name"
        )
);

This array has the values I'd like to combine together

$vals = array (
    "0" => "830680",
    "1" => "20",
    "2" => "Sullivan Avenue",
    "3" => "333000",
    "4" => "12",
    "5" => Array
        (
             "0" => "4",
             "1" => "Maryland",
        ),

    "6" => Array
        (
            "0" => "782",
            "1" => "baltimore",
            "2" => "Baltimore",
        )
);

When I try to do array_combine($keys, $val); I get 2 Notices about Array to string conversion

I guess array_combine only works on one dimensional arrays, any ideas on how to approach this?

If $keys was modified could it be combined with the values - problem is the shape of $keys is what I want to end up with?

2
  • 1
    the expected output is? Commented Apr 23, 2015 at 22:57
  • all the keys in the second array the same as the first one. Commented Apr 24, 2015 at 2:27

1 Answer 1

2

It can be done recursively.

function combine_recursive($keys, $values) {
    $result = array();
    $key = reset($keys);
    $value = reset($values);
    do {
        if (is_array($value)) {
            $result[key($keys)] = combine_recursive($key, $value);
        } else {
            $result[key($keys)] = $value;
        }
        $value = next($values);
    } while ($key = next($keys));
    return $result;
}

This works for me with your example arrays. I'm sure this will give you all kinds of weird results/errors if the array structures are different from each other at all.

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

1 Comment

This works great with the example, and I do expect the array structures to be identical. Thanks for your help.

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.