Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

use an array of keys and values to generate a string of addresses

for four days I am trying to figure out how to solve this, as well as googling it, and was no luck

I want to generate complete addresses from this array.

$arr = [
    "buildings" => [
        "group1" => [
            "b1" => [1,2,3,4],
            "b2" => [1,2,3]
        ],
        "group2" => [
            "b1" => [1,2]
        ]
    ],
    "villas" =>[
        "group1" => [
            "v1" => [1,2],
            "v2" => [1]
        ],
        "group2" => [
            "v1" => [1],
            "v2" => [1]
        ],
        "group3" => [
            "v1" => [1]
        ],
    ]
];

This is the needed output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

buildings/group1/b1/1
buildings/group1/b1/2
buildings/group1/b1/3
buildings/group1/b1/4
buildings/group1/b2/1
buildings/group1/b2/2
buildings/group1/b2/3
buildings/group2/b1/1
buildings/group2/b1/2
villas/group1/v1/1
villas/group1/v1/2
villas/group1/v2/1
villas/group2/v1/1
villas/group2/v2/1
villas/group3/v1/1

I tried this function but also it didn’t bring the wanted results

function test($array, $path = ""){
    foreach ($array as $key => $value) {
        if (is_array($value)){
            $path .= $key."/";
            test($value, $path);
        } else {
            echo $path.$value."<br>";
        }
    }
}
test($arr);

>Solution :

Here you go:

function flatten($arr, $prefix = '') {
    $result = [];
    foreach ($arr as $key => $value) {
        if (is_array($value)) {
            $result = array_merge($result, flatten($value, $prefix . $key . '/'));
        } else {
            $result[] = $prefix . $value;
        }
    }
    return $result;
}

// Usage
print_r(flatten($arr))

Returns an Array:

Array ( 
    [0] => buildings/group1/b1/1 
    [1] => buildings/group1/b1/2 
    [2] => buildings/group1/b1/3 
    [3] => buildings/group1/b1/4 
    [4] => buildings/group1/b2/1 
    [5] => buildings/group1/b2/2 
    [6] => buildings/group1/b2/3 
    [7] => buildings/group2/b1/1 
    [8] => buildings/group2/b1/2 
    [9] => villas/group1/v1/1 
    [10] => villas/group1/v1/2 
    [11] => villas/group1/v2/1 
    [12] => villas/group2/v1/1 
    [13] => villas/group2/v2/1 
    [14] => villas/group3/v1/1 
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading