odannyc
odannyc

Reputation: 718

Convert an array of simple arrays into an array of Associative arrays?

I'm using PHP for this and I'm using the array listed here: https://gist.github.com/aghouseh/3926213

So basically it's an array with State name, and within those state names is a list of counties, something like this:

$counties = array(
"Alabama" => array(
    "Autauga County",
    "Baldwin County",
    "Barbour County",
    "Bibb County")
"California => array(
    "Los angeles County",
    "San francisco county"));

So basically what I'm trying to accomplish is this:

$counties = array(
"Alabama" => array(
    "Autauga County" => "Autauga County",
    "Baldwin County" => "Baldwin County",
    "Barbour County" => "Barbour County",
    "Bibb County" => "Bibb County")
"California => array(
    "Los angeles County" => "Los angeles County",
    "San francisco county" => "San francisco county"));

I wanna make that second level array into an associative array. I tried to search for an answer and I came up with this but didn't work:

foreach ($counties as $state) {
        foreach ($state as $county) {
            array_combine($county, $county);
        }
    }

Upvotes: 0

Views: 46

Answers (2)

Markus AO
Markus AO

Reputation: 4889

Actually array_combine would be a fine and elegant way to do this. If only you used it at the right level and stored its result somewhere! Note that array_combine doesn't work by reference on the original array. It returns the result instead. Use this:

foreach($counties as &$states) {
    $states = array_combine($states, $states);
}

That's all the code you need to get this done.

Upvotes: 1

Gavriel
Gavriel

Reputation: 19237

Create a new array as you wish and replace the original with it:

foreach ($counties as $state => $x) {
    $c = array();
    foreach ($x as $county) {
        $c[$county] = $county;
    }
    $counties[$state] = $c;
}

Upvotes: 1

Related Questions