Search code examples
phparraysmultidimensional-arraygrouping

Split keys of a flat, associative array by last delimiter then build a 2d associative array using the key parts


I have pairs of keys identified by their respective ID like this:

array(
    'key_a_0' => $a,
    'key_a_1' => $a,
    'key_b_0' => $b,
    'key_b_1' => $b
    )

I need this structure:

array(
    '0' => array(
        'key_a' => $a,
        'key_b' => $b
    ),
    '1' => array(
        'key_a' => $a,
        'key_b' => $b
    )
)

What would be the best way to achieve this?


Solution

  • Provided this is exactly how all the data is present as, and stays as, this would then be simple to amend into the format you require with a simple foreach loop.

    $new = array();
    
    foreach($data as $key => $variable){
        list($name,$var,$index) = explode("_", $key);
        $new[$index][$name . '_' . $var] = $variable;
    }
    

    This returns;

    Array
    (
        [0] => Array
            (
                [key_a] => 5
                [key_b] => 10
            )
    
        [1] => Array
            (
                [key_a] => 5
                [key_b] => 10
            )
    
    )
    

    Example


    Ideally - you'd want to set your array structure at creation, as Dagon said.