0

How can I convert a flat array into a nested array where the nested keys are prefixed with the same value. For example say I have the following array:

[
    'name' => 'a',
    'content' => 'b',
    'author_fullName' => 'c',
    'author_email' => 'd',
    'author_role_name' => 'e'
]

Then the out of the array would be:

[
    'name' => 'a',
    'content' => 'b',
    'author' => [
        'fullName' => 'c',
        'email' => 'd',
        'role' => [
            'name' => 'e'
        ]
    ]
]

Ideally I'd like a solution using the built in array functions as I prefer functional syntax rather than using for loops. I'd appreciate the help. Thanks

nfplee
  • 7,643
  • 12
  • 63
  • 124
  • 1
    http://stackoverflow.com/questions/8243944/functions-to-get-set-values-in-multidimensional-arrays-dynamically – u_mulder Feb 10 '17 at 10:09
  • 1
    http://stackoverflow.com/questions/27929875/how-to-write-getter-setter-to-access-multi-level-array-by-key-names – u_mulder Feb 10 '17 at 10:10

2 Answers2

1

Try below code:

<?php

$a = [
 'name' => 'a',
 'content' => 'b',
 'author_fullName' => 'c',
 'author_email' => 'd',
 'author_role_name' => 'e'
];

$finalArray =[];
array_walk($a, function(&$value, $key) use(&$finalArray) {
 $indexes = explode('_',$key);
 foreach ($indexes as $index){
    $finalArray = &$finalArray[$index];
 }
 $finalArray = $value;
});


print_r($finalArray);
mith
  • 1,680
  • 1
  • 10
  • 12
  • Thanks this does the trick. I'll leave this open for now but I will mark it as the answer if nobody comes up with a better solution. – nfplee Feb 10 '17 at 12:19
0

Another solution

$delimiter = '_';
$result = [];
foreach($array as $k => $v)
{
    $split = explode($delimiter, $k, 2);//explode only as much as we need
    if(count($split) > 1)
    {
        if(!isset($result[$split[0]]))
        {
            $result[$split[0]] = [];
        }
        //this assumes we're not interested in more than two depths
        //in tandem with the explode limit
        $result[$split[0]][$split[1]] = $v;
    }
    else
    {
        $result[$k] = $v;
    }
}
Chibueze Opata
  • 9,856
  • 7
  • 42
  • 65