如何将数组分成更小的数组?

时间:2013-09-16 02:45:59

标签: php regex

我需要使用诸如空格之类的分隔符将数组分成更小的数组,而不是使用一定数量的字符(因此array_chunk将不适用于此而且这些答案How to break an array into a specified number of smaller arrays?因同样的原因无关紧要)。

示例:

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

想分开"一两三"在一个数组中使用三个元素(使用空格作为分隔符),对于接下来的两个元素使用相同的元素。这可以分为多维 数组也是如此。

1 个答案:

答案 0 :(得分: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",
  ),
)