Jump to content

[solved] adding an element to wire array during loop/iteration


gunter
 Share

Recommended Posts

I have a sorted list of calendar events, stored in a wire array. I want  iterate/loop through the wire array and at a specific condition I want split the actual element into two elements... so I use inserAfter() the actual element - this works wonderfull, but with foreach the loop does not know that the array is now an element bigger....

so foreach does not work, insertAfter() does work, but the new element does not show up during the loop

// $s is a wire array containing 10 Elements
$insert = new Event(5555);

foreach($s as $key => $event){
	if($key==5){
		 $s->insertAfter($insert, $event); //insert an new item when $key==5
	}
	echo $event;
}

this works... the inserted item is shown after inserting it into the array

$insert = new Event(5555);
$count=count($s);
$counter = 0;

while($counter <$count) {
	if($counter==5){
		 $s->insertAfter($insert, $s[$counter]);
		 $count++;
	}
    echo "<br>".$s[$counter]->start;
    $counter++;
} 

but I want a shorter/ more elegant solution

Link to comment
Share on other sites

Sorry guys, this is not what I need... inserting the array element should be IN the loop
I found some snippets here and will try it in the evening: 
https://stackoverflow.com/questions/2348077/change-initial-array-inside-the-foreach-loop

precede $value with &like so

$array = array('red', 'blue');
foreach($array as $key => &$value) {// <-- here
    $array[] = 'white';
    echo $value . '<br />';
}

A while loop would be a better solution.

while (list ($key, $value) = each ($array) ) {
    $array[] = 'white';
    echo $value . '<br />';
}

(edit: unfortunately this code did not work...)

 

Link to comment
Share on other sites

I will use this until I find a better solution

$value = $s->first();
while ($value) {
  	if($value->start==50){ //just an example to select an element 
 		$s->insertAfter($insert, $value);
 	}
    echo $value.'<br>';	
    $value = $s->getNext($value);
}

[edit] I have now the solution, I rewrote the iterator class for my wire array an now it works

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...