PHP - 将字符串拆分为多维数组的无环方法 [英] PHP - Loopless way to split a string into a multidimensional array

查看:28
本文介绍了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 - 将字符串拆分为多维数组的无环方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆