PHP - 无回路的方式将一个字符串分割成一个多维数组 [英] PHP - Loopless way to split a string into a multidimensional array

查看:126
本文介绍了PHP - 无回路的方式将一个字符串分割成一个多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何分割字符串转换成PHP中的多维数组不循环?

How do I split a string into a multidimensional array in PHP without loops?

我的字符串格式为A,5 | B,3 | C,8

推荐答案

如果没有实际上做的循环部分的基础上的 array_map + 爆炸 应该做的伎俩;例如,考虑到你正在使用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)

当然,code的这一部分可被重新写入到不使用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 ^^

结果
不过,我presume array_map 会遍历所有的阵列中的每个元素由返回爆炸 ...所以,即使环是不是在你的code,仍然会为一个...


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天全站免登陆