首页 > 解决方案 > 循环遍历嵌套数组php和前缀值

问题描述

读取数组中的所有前缀值。如果 slug 值是模块,则结果将是 api/v1/tenants/modules/{id},相反,如果 slug 值获取结果将是 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",
                    ]


                ],
            ],
        ],

数组列表

标签: phparraysjson

解决方案


您可以使用array_walk_recursive递归遍历数组,

$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);

演示

输出

api/v1/tenants/modules/{id}

推荐阅读