Home > Backend Development > PHP Tutorial > How to Compute the Cartesian Product of PHP Associative Arrays While Preserving Key-Value Pairs?

How to Compute the Cartesian Product of PHP Associative Arrays While Preserving Key-Value Pairs?

Patricia Arquette
Release: 2024-12-27 01:40:11
Original
748 people have browsed it

How to Compute the Cartesian Product of PHP Associative Arrays While Preserving Key-Value Pairs?

Finding Cartesian Product with PHP Associative Arrays, Preserving Key-Value Pairs

Given an associative array with multiple sub-arrays representing different attributes, the task is to compute the Cartesian product while preserving the keys and their corresponding values.

Rationale

For an array $input with N sub-arrays, where each sub-array has Cn elements, we can proceed with induction:

  • For N = 1, the Cartesian product is simply the input array itself.
  • Assuming we have the Cartesian product of the first N-1 sub-arrays, we can compute the product of the Nth sub-array by:

    • In each item (array) within the product, add the pair KN => VN,1.
    • For each value VN,2 to VN,CN, add a copy of each item to the product, changing the value of KN to VN,m (for all 2 ≤ m ≤ CN).

Code

function cartesian($input) {
    $result = [];

    while (list($key, $values) = each($input)) {
        if (empty($values)) {
            continue;
        }

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

            foreach ($result as &$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

Usage

$input = [
    'arm' => ['A', 'B', 'C'],
    'gender' => ['Female', 'Male'],
    'location' => ['Vancouver', 'Calgary'],
];

print_r(cartesian($input));
Copy after login

Will output the desired Cartesian product, preserving the keys and values:

Array
(
    [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.
Copy after login

The above is the detailed content of How to Compute the Cartesian Product of PHP Associative Arrays While Preserving Key-Value Pairs?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template