Home >Backend Development >PHP Tutorial >How to Calculate the Cartesian Product of PHP Associative Arrays while Preserving Keys?

How to Calculate the Cartesian Product of PHP Associative Arrays while Preserving Keys?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 13:58:13623browse

How to Calculate the Cartesian Product of PHP Associative Arrays while Preserving Keys?

Finding Cartesian Product with PHP Associative Arrays


Given an associative array, it's possible to determine its cartesian product while preserving its keys and utilizing them within the inner arrays.

Methodology


We can approach this problem through induction:



  1. For a single array, the cartesian product is a series of arrays with a single key-value pair representing each item in the original array.



  2. Assuming the product of the first N-1 arrays is known, adding the Nth array involves:



  3. For each existing product, append an element with the Nth array's key and the first value of the Nth array.




Repeating these steps ensures that the product of N arrays is achieved.


Implementation


function cartesian($input) {</p>
<pre class="brush:php;toolbar:false">$result = array();

foreach ($input as $key => $values) {
    if (empty($values)) {
        continue;
    }

    if (empty($result)) {
        foreach($values as $value) {
            $result[] = array($key => $value);
        }
    } else {
        $append = array();

        foreach($result as &amp;$product) {
            $product[$key] = array_shift($values);
            $copy = $product;

            foreach($values as $item) {
                $copy[$key] = $item;
                $append[] = $copy;
            }

            array_unshift($values, $product[$key]);
        }

        $result = array_merge($result, $append);
    }
}

return $result;

}

Example Usage


$input = array(</p>
<pre class="brush:php;toolbar:false">'arm' => array('A', 'B', 'C'),
'gender' => array('Female', 'Male'),
'location' => array('Vancouver', 'Calgary'),

);

print_r(cartesian($input));

Output


Array<br>(</p>
<pre class="brush:php;toolbar:false">[0] => Array
    (
        [arm] => A
        [gender] => Female
        [location] => Vancouver
    )

[1] => Array
    (
        [arm] => A
        [gender] => Female
        [location] => Calgary
    )

[2] => Array
    (
        [arm] => A
        [gender] => Male
        [location] => Vancouver
    )

...etc.

The above is the detailed content of How to Calculate the Cartesian Product of PHP Associative Arrays while Preserving Keys?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Day Setup LaravelNext article:Day Setup Laravel