我正在尝试拆分下面的数组。 array_chunk,splice等dint按预期给出输出。下面是输入数组:
Array ( [0] => Stephen
[1] => stephearce
[2] => s@gmail.com
[3] => Stephen
[4] => stephon
[5] => stn@kcl.ac.uk
[6] => Stephen
[7] => richard.stephens
[8] => rins@maneer.ac.uk
)
我想要如下:
Array (
[0] => Stephen
[1] => stephearce
[2] => s@gmail.com
)
Array (
[0] => Stephen
[1] => stephon
[2] => stn@kcl.ac.uk
)
Array (
[0] => Stephen
[1] => richard.stephens
[2] => rins@maneer.ac.uk
)
使用array_chunk如下所示,我不想这样:
Array (
[0] => Array (
[0] => Stephen
[1] => stephearce
[2] => s@gmail.com
)
[1] => Array (
[0] => Stephen
[1] => stephon
[2] => stn@kcl.ac.uk
)
[2] => Array (
[0] => Stephen
[1] => richard.stephens
[2] => rins@maneer.ac.uk
)
)
请帮忙!
答案 0 :(得分:0)
要做你要问的事情,你需要知道数组中有多少条目(除以你的块大小3,这样就可以列出这些变量:
list($var1, $var2, $var3) = array_chunk($myData, 3);
但如果您正在写csv,那么更容易做到:
$chunkedData = array_chunk($myData, 3);
foreach($chunkedData as $chunk) {
fputcsv($myFileHandle, $chunk);
}
答案 1 :(得分:0)
这是 working code :
<?
$arr = Array ( 0 => "Stephen",
1 => "stephearce",
2 => "s@gmail.com",
3 => "Stephen",
4 => "stephon",
5 => "stn@kcl.ac.uk",
6 => "Stephen",
7 => "richard.stephens",
8 => "rins@maneer.ac.uk",
);
print_r($arr);
foreach ($arr as $item){
if ($item == "Stephen"){
if (isset($newArr)) $output[] = $newArr;
$newArr = array();
}
$newArr[] = $item;
}
if (count($newArr) > 0) $output[] = $newArr;
print_r($output);
?>
您可以完全控制foreach循环 - 可以使用此数据执行任何操作