给出一个array()
,如下所示:
Array
(
[0] => 1
[1] => Lorem ipsum
[2] => dolor sit
[3] => amet
[4] => 2
[5] => consectetur
[6] => adipiscing elit
[7] => adipiscing elit
[8] => 3
[9] => Integer nec
[10] => odio
)
具有一组动态数字(1
,2
,3
,4
,5
等)。
实现这样的结果的一种更有效的方法是
Array
(
[1] => Array
(
[0] => 1
[1] => Lorem ipsum
[2] => dolor sit
[3] => amet
)
[2] => Array
(
[0] => 2
[1] => consectetur
[2] => adipiscing elit
[3] => adipiscing elit
)
[3] => Array
(
[0] => 3
[1] => Integer nec
[2] => odio
)
)
递增的数组值用作将数组拼接为单独的块的分割点:
(工作示例)https://3v4l.org/EqnIN
$exploded = array(
'1',
'Lorem ipsum',
'dolor sit',
'amet',
'2',
'consectetur',
'adipiscing elit',
'adipiscing elit',
'3',
'Integer nec',
'odio'
);
$array = array();
$a = false;
$count = 1;
$arraycount = count($exploded);
for ($i = 0; $i < $arraycount; $i++)
{
$countstring = $count + 1;
$countstring = (string)$countstring;
if ($exploded[$i] == $count)
{
$array[$count][] = $exploded[$i];
$a = true;
}
elseif ($a == true && $exploded[$i] == (string)$count)
{
$array[$count][] = $exploded[$i];
}
elseif ($a == true && $exploded[$i + 1] != $countstring)
{
$array[$count][] = $exploded[$i];
}
elseif ($a == true && $exploded[$i + 1] == $countstring)
{
$array[$count][] = $exploded[$i];
$count++;
$a = false;
}
}
答案 0 :(得分:3)
我相信这应该等同于您的代码:
$array = array();
$count = -1;
$nextcount = 1;
$arraycount = count($exploded);
for ($i = 0; $i < $arraycount; $i++) {
if ($exploded[$i] == $nextcount) {
$count++;
$nextcount++;
}
$array[$count][] = $exploded[$i];
}