wc_array_cartesian

Find all possible combinations of values from the input array and return in a logical order.

Description

(array) wc_array_cartesian( (array) $input ); 

Returns (array)

Parameters (1)

0. $input (array)
The input.

Usage

  1. if ( !function_exists( 'wc_array_cartesian' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-core-functions.php'; 
  3.  
  4. // The input. 
  5. $input = array(); 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wc_array_cartesian($input); 
  9.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-core-functions.php  
  1. function wc_array_cartesian( $input ) { 
  2. $input = array_filter( $input ); 
  3. $results = array(); 
  4. $indexes = array(); 
  5. $index = 0; 
  6.  
  7. // Generate indexes from keys and values so we have a logical sort order 
  8. foreach ( $input as $key => $values ) { 
  9. foreach ( $values as $value ) { 
  10. $indexes[ $key ][ $value ] = $index++; 
  11.  
  12. // Loop over the 2D array of indexes and generate all combinations 
  13. foreach ( $indexes as $key => $values ) { 
  14. // When result is empty, fill with the values of the first looped array 
  15. if ( empty( $results ) ) { 
  16. foreach ( $values as $value ) { 
  17. $results[] = array( $key => $value ); 
  18.  
  19. // Second and subsequent input sub-array merging. 
  20. } else { 
  21. foreach ( $results as $result_key => $result ) { 
  22. foreach ( $values as $value ) { 
  23. // If the key is not set, we can set it 
  24. if ( ! isset( $results[ $result_key ][ $key ] ) ) { 
  25. $results[ $result_key ][ $key ] = $value; 
  26. // If the key is set, we can add a new combination to the results array 
  27. } else { 
  28. $new_combination = $results[ $result_key ]; 
  29. $new_combination[ $key ] = $value; 
  30. $results[] = $new_combination; 
  31.  
  32. // Sort the indexes 
  33. arsort( $results ); 
  34.  
  35. // Convert indexes back to values 
  36. foreach ( $results as $result_key => $result ) { 
  37. $converted_values = array(); 
  38.  
  39. // Sort the values 
  40. arsort( $results[ $result_key ] ); 
  41.  
  42. // Convert the values 
  43. foreach ( $results[ $result_key ] as $key => $value ) { 
  44. $converted_values[ $key ] = array_search( $value, $indexes[ $key ] ); 
  45.  
  46. $results[ $result_key ] = $converted_values; 
  47.  
  48. return $results;