Search code examples
phparraysmultidimensional-arraygroupingdata-conversion

Split hyphenated keys of a flat associative array into first and second level keys of a 2d associative array


I need to convert a 1d array into a 2d array. The original keys are hyphenated. The new array should use the number before the hyphen as the new first level key and the string after the hyphen as the second level key.

Input:

Array
(
    [71-ctns] => 1
    [71-units] => 1
    [308-units] => 1
    [305-ctns] => 1
    [306-units] => 2
)

Desired output:

Array
(
    [71] => Array
        (
            [ctns] => 1
            [units] => 1
        )
    [308] => Array
        (
            [units] => 1
        )

    [305] => Array
        (
            [ctns] => 1
        )
    [306] => Array
        (
            [units] => 2
        )
)

Is this possible?


Solution

  • This should do it

    $merged = array();
    foreach($a as $k=>$v){
        $t = explode('-',$k);
        $id = intval($t[0]);
        if(!array_key_exists($id, $merged))
            $merged[$id] = array();
        $merged[$id][$t[1]] = $v;
    }
    

    EDIT:

    Sorry you should use explode instead of split.