Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Given the following input:

array('one/two/3',
      'one/four/0/5',
      'one/four/1/6',
      'one/four/2/7',
      'eight/nine/ten/11')

How can I convert it into this:

array(
   'one': array( 
        'two': 3,
        'four': array(5,6,7)
    )
   'eight': array(
        'nine': (
                'ten':11
            )
    }
 )
share|improve this question
1  
what have you tried so far? –  PoX Jul 26 '13 at 4:42

2 Answers 2

up vote 1 down vote accepted
$input = array ('one/two/3',
    'one/four/0/5',
    'one/four/1/6',
    'one/four/2/7',
    'eight/nine/ten/11');

$result = array ();
foreach ($input as $string) {
    $data      = array_reverse(explode('/', $string));
    $tmp_array = array ();
    foreach ($data as $val) {
        if (empty($tmp_array)) {
            $tmp_array = $val;
        } else {
            $tmp             = $tmp_array;
            $tmp_array       = array ();
            $tmp_array[$val] = $tmp;
        }
    }
    $result = array_merge_recursive($result, $tmp_array);
}
echo "<pre>";
print_r($result);
echo "</pre>";

Output:

Array
(
    [one] => Array
        (
            [two] => 3
            [four] => Array
                (
                    [0] => 5
                    [1] => 6
                    [2] => 7
                )

        )

    [eight] => Array
        (
            [nine] => Array
                (
                    [ten] => 11
                )

        )

)
share|improve this answer

It would be nice if we saw what you have tried.

$my_array = array('one/two/3',
'one/four/0/5',
'one/four/1/6',
'one/four/2/7',
'eight/nine/ten/11');

$result= array();   
foreach ($my_array as $val) {
$ref = & $result;
foreach (explode("/", $val) as $val) {
    if (!isset($ref[$val])) {
        $ref[$val] = array();
    }
    $ref = & $ref[$val];
}
$ref = $val;
}

var_dump($result);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.