0

我有一个数组,其数据设置如下

[0] =>"npage:new",
[1] =>"data:data",
[2] =>"data:data",
[3] =>"npage:new",
[4] =>"data:data",
[5] =>"data:data",
[6] =>"data:data",
[7] =>"npage:new",
[8] =>"data:data",
[9] =>"data:data", 

我试图重新排列数组,以便在每个“npage:new”它为它和下一个“npage:new”之间的数据创建另一个索引。直到最后一组没有“npage:new”但仍需要索引。例子:

[0] =>    
     "data:data",
     "data:data",
[1] =>
     "data:data",
     "data:data",
     "data:data",
[2] =>
     "data:data",
     "data:data",

我有以下内容,但它返回一个空白数组&我认为我把事情复杂化了。

    $source[] = the array
    $destination =  array();
$startval = "new";
$found = 0;
$starindex = 0;

foreach ($source as $index => $value){
if ($value === $startval) {
$found = $value;
$startindex = $index;
} 
    elseif ( $value === $found) {
$destination[] = array_slice($source, $startindex, $index - $startindex + 1);
$found = 0;
}
}
4

2 回答 2

0

自从我不写php以来已经很长时间了,但尝试这样的事情:

$source[] = the array
$destination =  array();
$startval = "new";
$ix = -1;

foreach ($source as $index => $value) {
    if ($value === $startval) {
        $ix++;
        $dest[$ix] = array();
    } 
    else {
        array_push($dest[$ix], $index.":".$value;
    }
}
于 2012-11-14T13:32:46.530 回答
0

见:http ://codepad.org/QCWTahnq

<?php
$source = array("npage:new", "data:data", "data:data", "npage:new", "data:data", "data:data", "data:data", "data:data", "npage:new", "data:data", "npage:new", "data:data", "data:data");
$final =  array();
$newpage = "npage:new";

$temp = array();

foreach ($source as $index => $value) {
    if ($value == $newpage) {
        if(!empty($temp)) {
            $final[] = $temp;
            $temp = array();
        }
    } 
    else {
        $temp[] = $value;
    }
}

if(!empty($temp))
   $final[] = $temp;

print_r($final);
?>
于 2012-11-14T13:38:57.030 回答