user4932891
user4932891

Reputation:

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?

Upvotes: -1

Views: 49

Answers (3)

mickmackusa
mickmackusa

Reputation: 47874

You can avoid rejoining the parts which make the second level key by using preg_split() to only split the keys on the last delimiter.

Code: (Demo)

$result = [];
foreach ($array as $k => $v) {
    [$k2, $k1] = preg_split('/_(?=[^_]+$)/', $k);
    $result[$k1][$k2] = $v;
}
var_export($result);

Upvotes: 0

Darren
Darren

Reputation: 13128

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.

Upvotes: 2

Jayawi Perera
Jayawi Perera

Reputation: 891

The following should do the job. This assumes, however, that the initial array comes in a specific order and that order is what is expected within each nested array in the final array, and that the keys in the initial array are always in that format.

$a = 5;
$b = 10;

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

$aFormattedArray = array();

foreach ($aRawArray as $sKey => $mValue) {
    $aKeyParts = explode('_', $sKey);
    $sExtractedKey = $aKeyParts[2];
    $sNewKey = $aKeyParts[0] . '_' . $aKeyParts[1];

    if (!isset($aFormattedArray[$sExtractedKey])) {
        $aFormattedArray[$sExtractedKey] = array();
    }

    $aFormattedArray[$sExtractedKey][$sNewKey] = $mValue;   
}

var_dump($aFormattedArray);

Upvotes: 0

Related Questions