-1

i have a simple code

data :

$data1 = array('1','2','3','4');
$data2 = array('1','2','3','4');
$data3 = array('1','2','3');

Logic :

for($a = 0; $a < count($data1); $a++){
    for($b = 0; $b < count($data2); $b++){
        for($c = 0; $c < count($data3); $c++){
        echo $data1[$a].$data2[$b].$data3[$c].'<br>';
        }
    }
}

in this sample total data is 3, if i have 4 data how to build logic will generate automatically

Above code is static and fixed only for 3 array inputs if there is a condition and the $data would be more than 3 then it will not work, so how can I use the code for more or less than 3 data variables

For example, If the input data is like,

$data1 = array('1','2','3','4');
$data2 = array('1','2','3','4');
$data3 = array('1','2','3');
$data4 = array(5,6);
$data5 = array(7,8);

Then how to use the loops in that case.

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • 2
    What you want to generate automatically? an array? if is that so, just pass the counter values in a function parameter, like `function counter($end) {//loop}` and now use `$end` as for loop end counter – Mr. Alien Oct 01 '13 at 05:11
  • @Mr.Alien: can you provide an answer? I don't think that the solution is such easy! – Jason OOO Oct 01 '13 at 05:14
  • @JasonOOO it's so easy, he needs 4, instead of 3, so the loop counter will end at 4, he needs a function, so he can simply pass an end counter value, now that's what I understand from his question – Mr. Alien Oct 01 '13 at 05:17
  • @Mr.Alien: no you are wrong, see this post http://stackoverflow.com/questions/17959127/php-array-join-each-sub-array-together-probability – Jason OOO Oct 01 '13 at 05:18
  • @JasonOOO Do you see the difference between numbers and letters? – Mr. Alien Oct 01 '13 at 05:20
  • I guess his question is hard to express, some one help him rephrase his words instead of flagging him and onhold his question? – Krypton Oct 01 '13 at 05:23
  • @Irfan try this, ` function getArrayList( $arrList,$index=0){ $subList = $lists = ''; if ( $index < count( $arrList )-1 ){$subList = getArrayList( $arrList, $index+1 );} foreach( $arrList[$index] as $item ){$lists[$item]=$subList;} return $lists; } $array = array(array(1,2,3),array(4,5),array(6,7),array(8,9)); $lists = getArrayList( $array ); function listData($lists,$d=array()) {foreach( $lists as $value => $r ){array_push( $d, $value );if ( is_array( $r ) ) {listData( $r, $d );}else{ echo implode( " ", $d ) ."
    ";} array_pop( $d ); }}listData( $lists ); ?>`
    – Rohan Kumar Oct 01 '13 at 06:10

1 Answers1

0

What about having an array of those arrays instead and then you iterate through that array?

i.e.

$data = array(
    array('1','2','3','4'),
    array('1','2','3','4'),
    array('1','2','3')
);

I guess you know how to do the rest...

Krypton
  • 3,337
  • 5
  • 32
  • 52