opportus opportus - 6 months ago 11
PHP Question

PHP Array Restructuration

I have pairs of values 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
)
)

Answer

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.

Comments