PHP基于自定义函数生成笛卡尔积的方法示例

这篇文章主要介绍了PHP基于自定义函数生成笛卡尔积的方法,结合具体实例形式分析了php使用数组运算模拟集合实现笛卡尔积运算的相关操作技巧,需要的朋友可以参考下。

本文实例讲述了PHP基于自定义函数生成笛卡尔积的方法,分享给大家供大家参考,具体如下:

  1. <?php
  2. $color = array('red', 'green');
  3. $size = array(39, 40, 41);
  4. $local = array('beijing', 'shanghai');
  5. echo "<pre>";
  6. print_r(combineDika($color, $size, $local));
  7. /**
  8. * 所有数组的笛卡尔积
  9. *
  10. * @param unknown_type $data
  11. */
  12. function combineDika() {
  13. $data = func_get_args();
  14. $cnt = count($data);
  15. $result = array();
  16. foreach($data[0] as $item) {
  17. $result[] = array($item);
  18. }
  19. for($i = 1; $i < $cnt; $i++) {
  20. $result = combineArray($result,$data[$i]);
  21. }
  22. return $result;
  23. }
  24. /**
  25. * 两个数组的笛卡尔积
  26. *
  27. * @param unknown_type $arr1
  28. * @param unknown_type $arr2
  29. */
  30. function combineArray($arr1,$arr2) {
  31. $result = array();
  32. foreach ($arr1 as $item1) {
  33. foreach ($arr2 as $item2) {
  34. $temp = $item1;
  35. $temp[] = $item2;
  36. $result[] = $temp;
  37. }
  38. }
  39. return $result;
  40. }
  41. ?>

运行结果:

  1. Array
  2. (
  3. [0] => Array
  4. (
  5. [0] => red
  6. [1] => 39
  7. [2] => beijing
  8. )
  9. [1] => Array
  10. (
  11. [0] => red
  12. [1] => 39
  13. [2] => shanghai
  14. )
  15. [2] => Array
  16. (
  17. [0] => red
  18. [1] => 40
  19. [2] => beijing
  20. )
  21. [3] => Array
  22. (
  23. [0] => red
  24. [1] => 40
  25. [2] => shanghai
  26. )
  27. [4] => Array
  28. (
  29. [0] => red
  30. [1] => 41
  31. [2] => beijing
  32. )
  33. [5] => Array
  34. (
  35. [0] => red
  36. [1] => 41
  37. [2] => shanghai
  38. )
  39. [6] => Array
  40. (
  41. [0] => green
  42. [1] => 39
  43. [2] => beijing
  44. )
  45. [7] => Array
  46. (
  47. [0] => green
  48. [1] => 39
  49. [2] => shanghai
  50. )
  51. [8] => Array
  52. (
  53. [0] => green
  54. [1] => 40
  55. [2] => beijing
  56. )
  57. [9] => Array
  58. (
  59. [0] => green
  60. [1] => 40
  61. [2] => shanghai
  62. )
  63. [10] => Array
  64. (
  65. [0] => green
  66. [1] => 41
  67. [2] => beijing
  68. )
  69. [11] => Array
  70. (
  71. [0] => green
  72. [1] => 41
  73. [2] => shanghai
  74. )
  75. )