PHP - 将字符串拆分为多维数组的无环方法

2022-01-04 00:00:00 string arrays php scripting

如何在没有循环的情况下在 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...

相关文章