PHP - Loopless way to split a string into a multidimensional array(PHP - 将字符串拆分为多维数组的无环方法)
问题描述
如何在没有循环的情况下在 PHP 中将字符串拆分为多维数组?
How do I split a string into a multidimensional array in PHP without loops?
我的字符串格式为"A,5|B,3|C,8"
推荐答案
没有你实际做循环部分,基于array_map + explode代码> 应该可以解决问题;例如,考虑到您使用的是 PHP 5.3 :
Without you actually doing the looping part, something based on array_map + explode should do the trick ; for instance, considering you are using PHP 5.3 :
$str = "A,5|B,3|C,8";
$a = array_map(
function ($substr) {
return explode(',', $substr);
},
explode('|', $str)
);
var_dump($a);
会得到你:
array
0 =>
array
0 => string 'A' (length=1)
1 => string '5' (length=1)
1 =>
array
0 => string 'B' (length=1)
1 => string '3' (length=1)
2 =>
array
0 => string 'C' (length=1)
1 => string '8' (length=1)
当然,这部分代码可以重写为不使用 lambda 函数,并使用 PHP <5.3 -- 但没那么有趣^^
Of course, this portion of code could be re-written to not use a lambda-function, and work with PHP < 5.3 -- but not as fun ^^
尽管如此,我认为 array_map 将遍历 explode 返回的数组的每个元素......所以,即使循环不在你的代码中,仍然会有一个...
Still, I presume array_map will loop over each element of the array returned by explode... So, even if the loop is not in your code, there will still be one...
这篇关于PHP - 将字符串拆分为多维数组的无环方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP - 将字符串拆分为多维数组的无环方法
基础教程推荐
- 在PHP中根据W3C规范Unicode 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
