php 路径变量如何实现的?

请求路径 ‘/user/{id}/type/{type}’;这个可能有N个变量
问题描述:我后端php请求别人接口,是path里面带参数的形式,不知道怎么封装比较方便。 如果一个一个拼接太麻烦了 ,不知道用php 怎么实现类似前端那种 比如传一个数组就能直接转成请求的url [ ‘id’=>12,’type’=>11],前端好像一些比如axios 好像自带路径传参请求这个功能

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

就是正则

$uri = '/user/{id}/type/{type}/{?simple}';
preg_match_all('/\{(.*?)\}/', $uri, $matches);
1年前 评论
php_yt (作者) 1年前
tiantian10000 (楼主) 1年前
讨论数量: 6

不知道是不是你想要的

路由文件

//routes/web.php
Route::post('/user/{id}/type/{type}', [App\Http\Controllers\UserController::class, 'show'])->name('users.show');

逻辑代码

        $arr = [
            [ 'id'=>12,'type'=>11,],
            [ 'id'=>1,'type'=>1,],
        ];
        foreach ($arr as $v){
            echo route('users.show',$v),PHP_EOL;
        }
//http://alon.test/user/12/type/11
//http://alon.test/user/1/type/1
1年前 评论
tiantian10000 (楼主) 1年前

就是正则

$uri = '/user/{id}/type/{type}/{?simple}';
preg_match_all('/\{(.*?)\}/', $uri, $matches);
1年前 评论
php_yt (作者) 1年前
tiantian10000 (楼主) 1年前

倒也没必要用正则,稍微调整一下数组的键名,直接用 strtr 就可以了。

<?php

$uri = '/user/{id}/type/{type}';
$data = ['{id}' => 12, '{type}' => 11];

var_dump(strtr($uri, $data));
// string(16) "/user/12/type/11"
1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!