2

This array is dynamic and can have any number of records and can have any level of nested array:

Array
(
    [name] => richard
    [email] => [email protected]
    [address] => Array
        (
            [city] => paris
            [zip] => 12121
        )

    [address1] => Array
        (
            [city] => paris
            [zip] => 12121
        )

    [address3] => Array
        (
            [city] => paris
            [zip] => 12121

        )

)

I am trying to construct a string from nested array keys. I need to construct string like this from keys using loop:

Result should be like:

 address.city
   address.zip
   address1.city
   address1.zip....so on

How can it be achieved using recursion ?

1
  • What about name and email keys? They're not listed in your result. Commented Feb 7, 2019 at 23:12

3 Answers 3

2

This recursive function will do what you want. It checks each item at the current level of the array, and if it is an array, appends the current key to all the keys of that array, recursing as deep as necessary. If the item isn't an array, it's key is simply appended to the output for that level.

function list_keys($array) {
    $output = array();
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            foreach (list_keys($v) as $path) {
                $output[] = "$k.$path";
            }
        }
        else {
            $output[] = $k;
        }
    }
    return $output;
}

print_r(list_keys($array));

Output (for your sample data)

Array (
    [0] => name
    [1] => email
    [2] => address.city
    [3] => address.zip
    [4] => address1.city
    [5] => address1.zip
    [6] => address3.city
    [7] => address3.zip 
)

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

Comments

0

To get this result, you just have to loop over the array - and if the items is an array again, loop over the inner item as well.

This could be done like this:

$str = '';
foreach ($array as $key => $item) {
    if (is_array($item)) {
        foreach ($item as $other_key => $dummy) {
            $str .= ($str ? "\n" : '') . $key . '.' . $other_key;
        }
    }
}

echo $str;

2 Comments

this maybe work, but only into 1st and 2nd level of array. Not recursion
Check the last sentence in the question
0
function func($arr, $prefix = '') : void {
    $prefix = $prefix!='' ? "$prefix." : "";
    foreach ($arr as $key => $value) {
        if (!is_array($value)) {
            echo "$prefix$key\n";
        }
        else {
            func($value, "$prefix$key");
        }
    }
}

func($theArrayInTheQuestion);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.