首頁 >後端開發 >php教程 >如何在 PHP 中產生多個數組的笛卡爾積?

如何在 PHP 中產生多個數組的笛卡爾積?

Patricia Arquette
Patricia Arquette原創
2024-11-15 14:03:03249瀏覽

How to Generate Cartesian Products of Multiple Arrays in PHP?

Creating Cartesian Products of Multiple Arrays in PHP

Consider a PHP array structure like the following:

$array[0][0] = 'apples';
$array[0][1] = 'pears';
$array[0][2] = 'oranges';

$array[1][0] = 'steve';
$array[1][1] = 'bob';

Objective: To generate a tabulated list of all possible combinations of elements from these arrays, without duplication.

Solution:

The concept of generating all possible combinations from multiple arrays is known as the "Cartesian product." There are several methods to achieve this in PHP.

One approach is to utilize PHP's array functions. The following code snippet implements the Cartesian product using func_get_args() and recursion:

function array_cartesian() {
    $_ = func_get_args();
    if(count($_) == 0)
        return array(array());
    $a = array_shift($_);
    $c = call_user_func_array(__FUNCTION__, $_);
    $r = array();
    foreach($a as $v)
        foreach($c as $p)
            $r[] = array_merge(array($v), $p);
    return $r;
}

To use this function, pass an arbitrary number of arrays as arguments. For example, to generate the Cartesian product of the above arrays:

$cross = array_cartesian(
    array('apples', 'pears',  'oranges'),
    array('steve', 'bob')
);

The result, stored in $cross, will be an array containing all possible combinations:

print_r($cross);

Output:

Array (
    [0] => Array (
        [0] => apples
        [1] => steve
    )
    [1] => Array (
        [0] => apples
        [1] => bob
    )
    [2] => Array (
        [0] => pears
        [1] => steve
    )
    [3] => Array (
        [0] => pears
        [1] => bob
    )
)

以上是如何在 PHP 中產生多個數組的笛卡爾積?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn