繁体   English   中英

遍历嵌套数组php和前缀值

[英]Loop through nested array php and prefix value

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


                ],
            ],
        ],

数组列表

您可以使用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}

我使用array-walk-recursive作为:

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

现在, $ps是前缀的数组。 然后您可以使用implode添加/

直播示例: 3v4l

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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