Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I needed to do the same and I tried the previous solutions posted here but could not make them work. I got a sample from this clever guy <a href="http://www.php.net/manual/en/ref.array.php#54979" rel="nofollow">http://www.php.net/manual/en/ref.array.php#54979</a>. However, his sample did not managed the concept of no repeating combinations. So I included that part. Here is my modified version, hope it helps:</p> <pre><code>$data = array( array('apples', 'pears', 'oranges'), array('steve', 'bob') ); $res_matrix = $this-&gt;array_cartesian_product( $data ); foreach ( $res_matrix as $res_array ) { foreach ( $res_array as $res ) { echo $res . " - "; } echo "&lt;br/&gt;"; } function array_cartesian_product( $arrays ) { $result = array(); $arrays = array_values( $arrays ); $sizeIn = sizeof( $arrays ); $size = $sizeIn &gt; 0 ? 1 : 0; foreach ($arrays as $array) $size = $size * sizeof( $array ); $res_index = 0; for ( $i = 0; $i &lt; $size; $i++ ) { $is_duplicate = false; $curr_values = array(); for ( $j = 0; $j &lt; $sizeIn; $j++ ) { $curr = current( $arrays[$j] ); if ( !in_array( $curr, $curr_values ) ) { array_push( $curr_values , $curr ); } else { $is_duplicate = true; break; } } if ( !$is_duplicate ) { $result[ $res_index ] = $curr_values; $res_index++; } for ( $j = ( $sizeIn -1 ); $j &gt;= 0; $j-- ) { $next = next( $arrays[ $j ] ); if ( $next ) { break; } elseif ( isset ( $arrays[ $j ] ) ) { reset( $arrays[ $j ] ); } } } return $result; } </code></pre> <p>The result would be something like this:<br/> apples - steve <br/> apples - bob <br/> pears - steve <br/> pears - bob <br/> oranges - steve <br/> oranges - bob <br/></p> <p>If you the data array is something like this:</p> <pre><code> $data = array( array('Amazing', 'Wonderful'), array('benefit', 'offer', 'reward'), array('Amazing', 'Wonderful') ); </code></pre> <p>Then it will print something like this:<br/></p> <p>Amazing - benefit - Wonderful<br/> Amazing - offer - Wonderful<br/> Amazing - reward - Wonderful <br/> Wonderful - benefit - Amazing <br/> Wonderful - offer - Amazing<br/> Wonderful - reward - Amazing <br/></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload