0

I have a little problem. I want to transform this:

$array['page']['article']['header'] = "Header";
$array['page']['article']['body'] = "Body";
$array['page']['article']['footer'] = "Footer";
$array['page']['news']['header'] = "Header";
$array['page']['news']['body'] = "Body";
$array['page']['news']['footer'] = "Footer";

Into this:

$array['page.article.header'] = "Header";
$array['page.article.body'] = "Body";
$array['page.article.footer'] = "Footer";
$array['page.news.header'] = "Header";
$array['page.news.body'] = "Body";
$array['page.news.footer'] = "Footer";

The number of dimensions is variable and can be times 0 or 10. I don't know if I used the right search term, but Google could not help me so far.

So if someone has a solution for me. Thanks

DerMudder
  • 13
  • 1
  • 1
    Loop over the array['page'], take the keys, concatenate them, store in a new array. But why do you want to change this at all? – B001ᛦ Aug 04 '20 at 13:04
  • What you can do, is iterate over the keys and values in a recurring loop. When using foreach you'll be able to access the key and the value, passing array from loop to loop using reference will allow you to modify it as you go. – Daniel Sepp Aug 04 '20 at 13:14

1 Answers1

1

You can loop over the array at hand. Now, if the current value is an array, recursively call that array to the function call. On each function call, return an array with key value pairs. When you get the output from your sub-array, attach current key value to all keys of that sub-array returned output.

Snippet:

<?php

function rearrange($array){
    $output = [];
    foreach($array as $key => $val){
        if(is_array($val)){
            $out = rearrange($val);
            foreach($out as $sub_key => $sub_val){
                $output[$key . "." . $sub_key] = $sub_val;
            }
        }else{
            $output[$key] = $val;
        }
    }
    
    return $output;
}

print_r(rearrange($array));

Demo: https://3v4l.org/40hjK

nice_dev
  • 17,053
  • 2
  • 21
  • 35