簡體   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