简体   繁体   English

遍历嵌套数组php和前缀值

[英]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}. 如果从属值为模块,则结果将为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",
                    ]


                ],
            ],
        ],

数组列表

You can use array_walk_recursive to traverse array recursively, 您可以使用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);

Demo . 演示

Output : 输出

api/v1/tenants/modules/{id}

I use array-walk-recursive as: 我使用array-walk-recursive作为:

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

Now, $ps is array of the prefix. 现在, $ps是前缀的数组。 Then you can use implode to add the / 然后您可以使用implode添加/

Live example: 3v4l 直播示例: 3v4l

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

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