I have an array with data set out as follows
[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",
Im trying to rearrange the array so that at each "npage:new" it creates another index for the data between it and the next "npage:new". until the last set which does not have "npage:new" but will still need an index. Example:
[0] =>
"data:data",
"data:data",
[1] =>
"data:data",
"data:data",
"data:data",
[2] =>
"data:data",
"data:data",
I have the following, but It returns a blank array & I think I'm over complicating things.
$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;
}
}
It's been a long time since I don't write php but try something like this:
$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;
}
}
See: 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);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.