php数组和网址URL参数的互相转换

php 2023-05-10 329次浏览

前言

接口调试和开发的过程中,相信很多小伙伴都会经常用到数组和url参数的相互转换来模拟请求。其实不用自己再通过foreach或implode之类的手动实现,php自身的函数库给我们提供了两个方法,完全够用:

一、http_build_query

将数据转换为URL参数格式,返回一个 URL 编码后的字符串。

示例:

$arr = [
    'name'        => 'ngxcode',
    'url'     => 'https://www.ngxcode.com',
    'flowid'  => '1001035',
    'desc'        => 'php share'
];

echo http_build_query($arr) . "\n";
echo http_build_query($arr, '', '&');

输出:

name=ngxcode&url=https%3A%2F%2Fwww.ngxcode.com&flowid=1001035&desc=php+share
name=ngxcode&url=https%3A%2F%2Fwww.ngxcode.com&flowid=1001035&desc=php+share

二、parse_str

URL参数字符串转为数组,将字符串解析成多个变量

示例:

$url_params = 'name=ngxcode&url=https%3A%2F%2Fwww.ngxcode.com&flowid=1001035&desc=php+share';
//如果设置了第二个变量 result,变量将会以数组元素的形式存入到这个数组,作为替代。
parse_str($url_params, $result);

print_r($result);

输出

Array
(
   [name] => ngxcode
   [url] => https://www.ngxcode.com
   [flowid] => 1001035
   [desc] => php share
)

PHP官方文档

以下为两个函数的官方文档介绍,需要更复杂转换和解析需求的,可查看文档使用
https://www.php.net/manual/zh/function.http-build-query.php
https://www.php.net/manual/zh/function.parse-str.php

php数组和网址URL参数的互相转换

喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址