合并/乘以数组中的缺失值

时间:2019-03-13 21:26:58

标签: php

我很难找到适当的逻辑来合并/相乘字符串数组。 看看下面的示例,我有2个数组。

第一个数组:

 ["Services"]=>
  array(2) {
    [0]=>
    string(15) "Website Service"
    [1]=>
    string(17) "WordPress Service"
  }

第二个数组:

["City"]=>
  array(3) {
    [0]=>
    string(7) "New York"
    [1]=>
    string(6) "Los Angeles"
    [2]=>
    string(7) "Chicago"
  }

我想要的是像3 * 2 = 6例子一样将其合并:

array(6){
    0 =>  [
        "Service" => "Website Service",
        "City" => "New York"
    ],
    1 =>  [
        "Service" => "Website Service",
        "City" => "Los Angeles"
    ],
    2 =>  [
        "Service" => "Website Service",
        "City" => "Chicago"
    ],
    3 =>  [
        "Service" => "Wordpress Service",
        "City" => "New York"
    ],
    4 =>  [
        "Service" => "Wordpress Service",
        "City" => "Chicago"
    ],
    5 =>  [
        "Service" => "Wordpress Service",
        "City" => "Los Angeles"
    ],
}

忘记提及,该数组将是动态的。当前示例不仅有2个! 预先感谢

1 个答案:

答案 0 :(得分:4)

如果存在动态输入数组,则在合并它们时需要考虑一个递归解决方案。

这是一个可行的解决方案:

// function to make combinations of input arrays
function combinations($arrays) {
    $result = array(array());
    foreach ($arrays as $property => $property_values) {
        $tmp = array();
        foreach ($result as $result_item) {
            foreach ($property_values as $property_value) {
                $tmp[] = array_merge($result_item, array($property => $property_value));
            }
        }
        $result = $tmp;
    }
    return $result;
}
$combinations = combinations(
    array(
        'Services' => array('Website Service', 'Wordpress Service'), // this can be your services array
        'City' => array('New York', 'Chicago', 'Los Angeles'), // cities array
        'Zip' => array('90001', '90002'), // zip array and you can add more next to it
        // add more arrays here 
    )
);

// print all combinations
print_r($combinations);

这里是DEMO

提示(由于建议的修改而添加):

您还可以在PHP 5.4和更高版本中初始化类似[]的数组。

PHP 5.4之前的版本:

$array = array();

PHP 5.4和更高版本

$array = [];

开销没有区别,因为就编译器/解析器而言,它们是完全同义词。如果需要它来支持旧版本的PHP,请使用以前的语法。