I have an associative array as follows:
$myarray = array('a'=>array(), 'b'=>array(), 'c'=>array(), 'd'=>array());
I want to be able to get all pairs of elements in the array. If it wasn't an associative array, I would use nested for loops, like:
for($i=0; $i<count($myarray); $i++) {
for($j=$i+开发者_如何学编程1; $j<count($myarray); $j++) {
do_something($myarray[$i], $myarray[$j]);
}
}
I have looked at using foreach loops, but as the inner loop goes through ALL elements, some pairs are repeated. Is there a way to do this?
Thanks!
The array_values() function returns an integer-indexed array containing all the values, so you can use it to obtain a list that you can iterate with a for.
Otherwise you can 'destroy' the array this way:
while($k = array_pop($my_array)) {
foreach($my_array as $j){
do_something($k, $j);
}
}
Try:
$keys = array_keys($myarray);
$c = count($myarray);
foreach ($keys as $k => $key1) {
for ($i = $k + 1; $i < $c; $i ++) {
dosomething($myarray[$key1], $myarray[$keys[$i]]);
}
}
精彩评论