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
Release: 2024-12-26 13:58:13
Original
618 people have browsed it

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><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;
Copy after login

}

Example Usage


$input = array(</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">'arm' => array('A', 'B', 'C'),
'gender' => array('Female', 'Male'),
'location' => array('Vancouver', 'Calgary'),
Copy after login

);

print_r(cartesian($input));

Output


Array<br>(</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><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
    )
Copy after login

...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!

source:php.cn
Previous article:Day Setup Laravel Next article:Is Using Both `isset()` and `!empty()` in PHP Input Validation Redundant?
Statement of this Website
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
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template