Forum Moderators: coopster
array (
0 = > 'dog',
1 = > 'cat',
2 = > 'cat',
3 = > 'cat',
4 = > 'dog',
5 = > 'cat',
6 = > 'dog',
7 = > 'cat',
8 = > 'cat',
9 = > 'cat'
)
What I need to do is loop through this array and get all the values between dog #1 and dog #2. They can go into another array...no problem. Then I need the values between dog #2 and dog #3 and so on until the array is done. Here is how it is structured... Basically "dog" is the parent and "cat" is the child... I have been looking at this all day and cant get my head around how to do this...any help would be appreciated.
$mixed_array = what you posted as the array
$result_array = array();
$index = 0;
foreach($mixed_array as $key => $value){
if( $value == 'dog') {
$result_array[$index] = array();
$index++;
} else {
$result_array[$index][] = $value;
}
}
Now the result_array will hold 3 entries at the top level and for each entry you have an array that you can parse for the cat values or retrieve its count.
for($i=0, $j=count($result_array); $i<$j; $i++) {
for($x=0, $y=count($result_array[$i]); $x<$y; $x++ ){
// Do something with this cat value
}
}
This example does not rely on keys. If the keys are integers with an incremental value as listed and the array values are just dog and cat, it can be simplified by subtracting the next dog index from the previous and reference the original array.