Is there a way with a PHP Iterator object to sometimes return multiple items from a single item?
For example, suppose I have an array:
$a = ['1','2','3','double 6','4'];
and I want to have an Iterator object that takes this and produces the following items:
You have to make of definite array for such string like
"double"=>2,"triple"=>3,"quadruple"=>4, "quintuple"=>5
<?php
$str = ["double"=>2,"triple"=>3,"quadruple"=>4, "quintuple"=>5];
$a = ['1','2','3','double 6','4'];
foreach($a as $key=>$val){
$val = explode(" ",$val);
if(count($val) > 1){
$a[$key] = $val[1];
for($i=1;$i<$str[$val[0]];$i++){
$a[] = $val[1];
}
}
}
sort($a);
print_r($a);
?>
One way that has occurred to me since posting the question is to use a Generator instead:
function my_iteration($data) { foreach ($data as $item) { if (IS DOUBLE) { yield $item; yield $item; } else { yield $item; } } }
This looks like flattening the array. If you are not worried about the memory you can use an initial array in the following form:
$array = ['1', '2', '3', ['6', '6'], '4'];
And then use RecursiveIteratorIterator
:
function flatArray1($array): iterator
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $item) {
yield $item;
}
}
print_r(iterator_to_array(flatArray1($array)));
If you want to use less memory you can use a kind of zipped version of an initial array:
$array = ['1', '2', '3', [2, '6'], '4'];
function flatArray2($array): iterator
{
foreach ($array as $item) {
if (is_array($item)) {
[$count, $item] = $item;
while ($count) {
yield $item;
$count -= 1;
}
continue;
}
yield $item;
}
}
print_r(iterator_to_array(flatArray2($array)));
Here is the demo.