简体   繁体   中英

Loop through nested array php and prefix value

Reads all the prefix value in an array. If slug value is modules the result would be api/v1/tenants/modules/{id}, in contrast if slug value fetch the result would be api/v1/tenants/fetch/{id}.

        "slug" => "api",
        "children" => [
            "prefix" => "v1",
            "slug" => "v1",
            "children" => [
                "prefix" => "tenants",
                "slug" => "tenants",
                "children" => [
                    [
                        "prefix" => "fetch/{id}",
                        "slug" => "fetch",
                    ],
                    [
                        "prefix" => "modules/{id}",
                        "slug" => "modules",
                    ]


                ],
            ],
        ],

数组列表

You can use array_walk_recursive to traverse array recursively,

$res = [];
// & so that it keeps data of $res in every loop
array_walk_recursive($arr, function ($item, $key) use (&$res) {
    if ($key == 'prefix') {
        $res[] = $item; // fetching only prefix values recursively
    }

});
// this is your generated url
echo implode("/", $res);

Demo .

Output :

api/v1/tenants/modules/{id}

I use array-walk-recursive as:

function getPrefix($v, $k) { global $ps; if ($k == "prefix") $ps[] = $v; }
array_walk_recursive($arr, 'getPrefix');

Now, $ps is array of the prefix. Then you can use implode to add the /

Live example: 3v4l

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM