将字符串拆分为五个一组

时间:2014-05-26 06:20:55

标签: php string

我有这个字符串:

string='101,102,103,105,201,250,2564,245564,212,2415,2102,5645,656';

我想将其拆分为5个小组。

输出应为:

array
{
    [0]=101,102,103,105,201
    [1]=250,2564,245564,212,2415
    [2]=2102,5645,656
}

2 个答案:

答案 0 :(得分:0)

试试这个

$str = "101,102,103,105,201,250,2564,245564,212,2415,2102,5645,656";

$arr = explode(",", $str);
$arr_chunk = array_chunk($arr, 5);

$arr_output = array();
foreach($arr_chunk as $arr_val)
{
  $arr_output[] = implode(",", $arr_val);
}

print_r($arr_output);

输出:

Array
(
    [0] => 101,102,103,105,201
    [1] => 250,2564,245564,212,2415
    [2] => 2102,5645,656
)

参见 FIDDLE DEMO

答案 1 :(得分:0)

另一种方法

<?php
$string = '101,102,103,105,201,250,2564,245564,212,2415,2102,5645,656';
$parts  = explode(",", $string);   
$cnt    = count($parts)/5;
for($i=0; $i<ceil($cnt); $i++) { 
   $arr[$i] = implode(",", array_slice($parts, $i*5, 5));
}
print_r($arr);
?>