Knide
Knide

Reputation: 131

PHP Flatten Multi Dimensional Array into String

I have this Array:

$input_array = array(
    'one' => array(
            'two' => '3',
            'four' => array(5,6,7)
        ),
    'eight' => array(
            'nine' =>  array(
                    'ten' => '11'
                )
        )

);

I want the output to be:

one/two:3 
one/four/0:5 
one/four/1:6 
one/four/2:7 
eight/nine/ten:11

I have managed to make this function/code:

function flatten($array) {
    if (is_array($array)) {
        //get the key and value pair of the array
        foreach ($array as $key => $value) {

            if (is_array($value)) {
                echo $key.'/';
            } else {
                echo $key.":".$value."<br/>\n";
            }

            flatten($value);
        }

    } else {
        return false;
    }


}

flatten($input_array);

Currently it outputs:

one/two:3
four/0:5
1:6
2:7
eight/nine/ten:11

The 1st and last line are correct, but in the middle it's not the output I wanted, I know I am close, just need more modification. Anyone can help? Thanks!

Upvotes: 1

Views: 394

Answers (2)

arkascha
arkascha

Reputation: 42935

You can implement a simple recursive strategy:

<?php
$input = [
    'one' => [
        'two' => '3',
        'four' => [5, 6, 7 ]
    ],
    'eight' => [
        'nine' => [
            'ten' => '11'
        ]
    ]
];

$output = [];
$path = [];

function createPath($entry, $path, &$output) {
    if (is_array($entry)) {
        foreach ($entry as $key => $value) {
            createPath($value, array_merge($path, [$key]), $output);
        }
    } else {
        $output[] = implode('/', $path) . ':' . $entry;
    }
};

createPath($input, $path, $output);

print_r($output);

The output of above code obviously is:

Array
(
    [0] => one/two:3
    [1] => one/four/0:5
    [2] => one/four/1:6
    [3] => one/four/2:7
    [4] => eight/nine/ten:11
)

Upvotes: 0

splash58
splash58

Reputation: 26153

save path until a leaf item and then echo:

function flatten($array, $prefix='') {
    if (is_array($array)) {
        //get the key and value pair of the array
        foreach ($array as $key => $value) {

            if (is_array($value)) {
                // call with `path to this array` 
                flatten($value, $prefix . $key.'/');
            } else {
                echo $prefix.$key.":".$value."<br/>\n";
            }
        }
    } else {
        return false;
    }
}

demo on eval.in

Upvotes: 3

Related Questions