遍历嵌套数组php和前缀值

时间:2019-06-27 05:46:17

标签: php arrays json

读取数组中的所有前缀值。如果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",
                    ]


                ],
            ],
        ],

Array list

2 个答案:

答案 0 :(得分:2)

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

输出

api/v1/tenants/modules/{id}

答案 1 :(得分:2)

我将array-walk-recursive用作:

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

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

实时示例:3v4l