Решение, которое работает для массива с любым количеством индексов, которые должны быть сгруппированы. Он просто ищет префикс &
и добавляет новые значения в запись животных.
$zooAmp = array(
'&dog&',
'*1*',
'one',
'&cat&',
'*2*',
'two',
'&mouse&',
'*3*',
'three',
'&dog&',
'*4*',
'four'
);
$zooStar = array(
'*1*',
'&dog&',
'one',
'*2*',
'&cat&',
'two',
'*3*',
'&mouse&',
'three',
'*4*',
'&dog&',
'four'
);
function & refactor(array $unfactored) {
$len = count($unfactored);
$data = array();
if ($len<3) {
return $data;
}
if ($unfactored[0][0]=='&') {
//this algorithm isn't too bad, just loop through and add the ones starting with
//'&' to the data, and write everything from that index down to the next '&'
//into the created index in data.
$i=0;
while ($i<$len) {
if (!array_key_exists($unfactored[$i], $data))
$data[$unfactored[$i]] = array();
//save to $arr for easier reading and writing
$arr = &$data[$unfactored[$i]];
$index = count($arr);
$arr[$index] = array();
for ($c=$i+1; $c<$len && $unfactored[$c][0]!='&'; $c++) {
$arr[$index][] = $unfactored[$c];
}
$i = $c;
}
} elseif ($unfactored[0][0]=='*') {
//this algorithm is a bit harder, but not so bad since we've already done the
//basic algorithm above. We just need to store the ones with a '*' and then
//add them back into the array after it's been created.
$i=0;
$unorganizedItem = NULL;
while ($i<$len) {
$key = $unfactored[$i];
if ($key[0]=='*') {
$unorganizedItem = $key;
$i++;
} elseif ($key[0]=='&') {
if(!array_key_exists($key, $data))
$data[$key] = array();
//save to $arr for easier reading and writing
$arr = &$data[$key];
$index = count($arr);
$arr[$index][] = $unorganizedItem;
$unorganizedItem = null;
for ($c=$i+1; $c<$len && $unfactored[$c][0]!='&'; $c++) {
if ($unfactored[$c][0]=='*') {
$unorganizedItem = $unfactored[$c];
} else {
$arr[$index][] = $unfactored[$c];
}
}
$i = $c;
}
}
}
return $data;
}
print_r(refactor($zooAmp));
print_r(refactor($zooStar));
Печать:
Array
(
[&dog&] => Array
(
[0] => Array
(
[0] => *1*
[1] => one
)
[1] => Array
(
[0] => *4*
[1] => four
)
)
[&cat&] => Array
(
[0] => Array
(
[0] => *2*
[1] => two
)
)
[&mouse&] => Array
(
[0] => Array
(
[0] => *3*
[1] => three
)
)
)
Array
(
[&dog&] => Array
(
[0] => Array
(
[0] => *1*
[1] => one
)
[1] => Array
(
[0] => *4*
[1] => four
)
)
[&cat&] => Array
(
[0] => Array
(
[0] => *2*
[1] => two
)
)
[&mouse&] => Array
(
[0] => Array
(
[0] => *3*
[1] => three
)
)
)