SoulieBaby
SoulieBaby

Reputation: 5471

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?

Upvotes: 0

Views: 191

Answers (4)

mickmackusa
mickmackusa

Reputation: 47874

It is not necessary to declare an empty parent array when pushing child elements with square brace syntax.

For improved readability, use symmetric array destructuring with the exploded key string.

PHP will auto-magically convert the numeric string keys to be integer-typed.

Code: (Demo)

$array = [
    '71-ctns' => 1,
    '71-units' => 1,
    '308-units' => 1,
    '305-ctns' => 1,
    '306-units' => 2,
];

$result = [];
foreach ($array as $k => $v) {
    [$id, $label] = explode('-', $k);
    $result[$id][$label] = $v;
}
var_export($result);

Output:

array (
  71 => 
  array (
    'ctns' => 1,
    'units' => 1,
  ),
  308 => 
  array (
    'units' => 1,
  ),
  305 => 
  array (
    'ctns' => 1,
  ),
  306 => 
  array (
    'units' => 2,
  ),
)

Upvotes: 0

Sanjeev Chauhan
Sanjeev Chauhan

Reputation: 4097

Find below code to restructure a predefined php array

<?php
$newArray=array();
$result = array("71-ctns"=>1,"71-units"=>1,"308-ctns"=>1,"308-units"=>1,"305-units"=>1,"306-units"=>2);
if(is_array($result) && count($result)>0) {
    foreach($result as $key=>$val) {
        $getKeyArray = explode("-",$key);
        $newArray[$getKeyArray[0]][$getKeyArray[1]] =$val;      
    }
}
print"<pre>";
print_r($newArray);
?>

Upvotes: 1

cwallenpoole
cwallenpoole

Reputation: 81988

Yes, but you need to loop (note: array_map can also work, but this example is more explicit):

$fin = array();
foreach( $complex as $item => $val ) 
{
    $pieces = explode('-', $item);
    $fin[$pieces[0]] = isset($fin[$pieces[0]])?:array();
    $fin[$pieces[0]][$pieces[1]] = $val;
}

Upvotes: 1

GWW
GWW

Reputation: 44093

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.

Upvotes: 2

Related Questions