Click here to Skip to main content
15,902,189 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a for loop like bellow:
PHP
$a = array('a', 'b', 'c', 'd', 'e', 'g');
$b = array('1', '2');
$count_a = count($a); //count $a
$count_b = count($b); //count $b

$u = 0;
for($i = 0; $i < $count_a; $i++){
    $result[] = $a[$i].'-'.$b[$u];
    $u++;
    if($u == $count_b){
        print_r($result);
        $u = 0;
    }
}

And result for it:
PHP
Array
(
    [0] => a-1
    [1] => b-2
)
Array
(
    [0] => a-1
    [1] => b-2
    [2] => c-1
    [3] => d-2
)
Array
(
    [0] => a-1
    [1] => b-2
    [2] => c-1
    [3] => d-2
    [4] => e-1
    [5] => g-2
)

I want the result to be:
PHP
Array
(
    [0] => a-1
    [1] => b-2
)
Array
(
    [2] => c-1
    [3] => d-2
)
Array
(
    [4] => e-1
    [5] => g-2
)

What I have to do? please help me!

What I have tried:

I try search google in 1 day but it fail
Posted
Updated 28-Sep-17 23:27pm

You have to clear the result array too after printing it out:
PHP
for($i = 0; $i < $count_a; $i++){
    $result[] = $a[$i].'-'.$b[$u];
    $u++;
    if($u == $count_b){
        print_r($result);
        $u = 0;
        unset($result);
    }
}
 
Share this answer
 
Another solution
<?php
$a = array('a', 'b', 'c', 'd', 'e', 'g');
$b = array('1', '2');
$count_a = count($a); //count $a
$count_b = count($b); //count $b
 
for($i=0;$i<$count_a;) {
  for($j=0;$j<$count_b;$j++, $i++) {
    $result[$i] = $a[$i]."-".$b[$j];
  }
  print_r($result);
  unset($result);
}


But if you want them all in one array

<?php
$a = array('a', 'b', 'c', 'd', 'e', 'g');
$b = array('1', '2');
$count_a = count($a); //count $a
$count_b = count($b); //count $b
 
for($i=0;$i<$count_a;) {
  for($j=0;$j<$count_b;$j++, $i++) {
    $result[$i] = $a[$i]."-".$b[$j];
  }
}
  print_r($result);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900