-2

我需要使用分隔符(例如空格)将数组分解为较小的数组,而不是使用一定数量的字符(因此 array_chunk 对此不起作用,这些答案如何将数组分解为指定数量的较小数组?不是出于同样的原因相关)。

例子:

$array1 = ("One two three","four five six","seven eight nine");

想将“一二三”拆分为一个数组中的三个元素(使用空格作为分隔符),接下来的两个元素也是如此。这也可以拆分为多维数组。

4

1 回答 1

2
php> $array1 = array("One two three","four five six","seven eight nine");

php> =array_map(function($a){return explode(' ',$a);},$array1)
array(
  0 => array(
    0 => "One",
    1 => "two",
    2 => "three",
  ),
  1 => array(
    0 => "four",
    1 => "five",
    2 => "six",
  ),
  2 => array(
    0 => "seven",
    1 => "eight",
    2 => "nine",
  ),
)

匿名函数可以更改为您认为合适的任何方式。正则表达式,随便。

编辑根据您的评论:

php> $array1 = array("One two three","four five,six","seven,eight nine");

php> =array_map(function($a){return preg_split('/[ ,]/',$a);},$array1)
array(
  0 => array(
    0 => "One",
    1 => "two",
    2 => "three",
  ),
  1 => array(
    0 => "four",
    1 => "five",
    2 => "six",
  ),
  2 => array(
    0 => "seven",
    1 => "eight",
    2 => "nine",
  ),
)
于 2013-09-16T02:56:53.120 回答