首頁 > 後端開發 > php教程 > PHP自訂函數產生笛卡兒積

PHP自訂函數產生笛卡兒積

WBOY
發布: 2016-08-08 09:26:27
原創
1405 人瀏覽過
<?php
	$color = array(&#39;red&#39;, &#39;green&#39;);
	$size = array(39, 40, 41);
	$local = array(&#39;beijing&#39;, &#39;shanghai&#39;);
	
	echo "<pre class="brush:php;toolbar:false">";
	print_r(combineDika($color, $size, $local));
	
	/**
	 * 所有数组的笛卡尔积
	 *
	 * @param unknown_type $data
	 */
	function combineDika() {
		$data = func_get_args();
		$cnt = count($data);
		$result = array();
		foreach($data[0] as $item) {
			$result[] = array($item);
		}
		for($i = 1; $i < $cnt; $i++) {
			$result = combineArray($result,$data[$i]);
		}
		return $result;
	}
	 
	/**
	 * 两个数组的笛卡尔积
	 *
	 * @param unknown_type $arr1
	 * @param unknown_type $arr2
	 */
	function combineArray($arr1,$arr2) {
		$result = array();
		foreach ($arr1 as $item1) {
			foreach ($arr2 as $item2) {
				$temp = $item1;
				$temp[] = $item2;
				$result[] = $temp;
			}
		}
		return $result;
	}
?>
登入後複製

運行結果:

Array
(
    [0] => Array
        (
            [0] => red
            [1] => 39
            [2] => beijing
        )

    [1] => Array
        (
            [0] => red
            [1] => 39
            [2] => shanghai
        )

    [2] => Array
        (
            [0] => red
            [1] => 40
            [2] => beijing
        )

    [3] => Array
        (
            [0] => red
            [1] => 40
            [2] => shanghai
        )

    [4] => Array
        (
            [0] => red
            [1] => 41
            [2] => beijing
        )

    [5] => Array
        (
            [0] => red
            [1] => 41
            [2] => shanghai
        )

    [6] => Array
        (
            [0] => green
            [1] => 39
            [2] => beijing
        )

    [7] => Array
        (
            [0] => green
            [1] => 39
            [2] => shanghai
        )

    [8] => Array
        (
            [0] => green
            [1] => 40
            [2] => beijing
        )

    [9] => Array
        (
            [0] => green
            [1] => 40
            [2] => shanghai
        )

    [10] => Array
        (
            [0] => green
            [1] => 41
            [2] => beijing
        )

    [11] => Array
        (
            [0] => green
            [1] => 41
            [2] => shanghai
        )

)
登入後複製


以上就介紹了PHP自訂函數產生笛卡兒積,包括了方面的內容,希望對PHP教學有興趣的朋友有幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板