PHP计算笛卡尔积

时间:2019-03-27 13:44:16

标签: php cartesian-product

我正在研究将多维数组中的数据转换为适合旧式SQL表的模型的层。

数据看起来像这样

array(4) {
  "idnumber" =>
  array(1) {
    [0] =>
    string(6) "123456"
  }
  "names" =>
  array(2) {
    [0] =>
    string(8) "name1"
    [1] =>
    string(8) "name2"
  }
  "keycodes" =>
  array(3) {
    [0] =>
    int(101)
    [1] =>
    int(102)
    [2] =>
    int(103)
  }
}

可以有任意数量的外部元素,也可以有任意数量的内部元素。

我无法绕过头来遍历它们并生成它(密钥无关紧要,这只是我对它们进行分组的初衷)

array() {
  "123456name1101" =>
  array(3){
    [0] =>
    string(6) "123456"
    [1] =>
    string(8) "name1"
    [2] =>
    int(101)
  }
  "123456name2101" =>
  array(3){
    [0] =>
    string(6) "123456"
    [1] =>
    string(8) "name2"
    [2] =>
    int(101)
  }
  "123456name1102" =>
  array(3){
    [0] =>
    string(6) "123456"
    [1] =>
    string(8) "name1"
    [2] =>
    int(102)
  }
  "123456name2102" =>
  array(3){
    [0] =>
    string(6) "123456"
    [1] =>
    string(8) "name2"
    [2] =>
    int(102)
  }
  "123456name1103" =>
  array(3){
    [0] =>
    string(6) "123456"
    [1] =>
    string(8) "name1"
    [2] =>
    int(103)
  }
  "123456name2103" =>
  array(3){
    [0] =>
    string(6) "123456"
    [1] =>
    string(8) "name2"
    [2] =>
    int(103)
  }
}

我该怎么做?

谢谢

1 个答案:

答案 0 :(得分:1)

这是一些计算叉积的代码。这不是我的代码,几年前我在网上某个地方找到它,此后一直在使用它。我不记得它的来源。

function crossProduct($array1=[], $array2=[], $_=[]) {
    $_ = 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;
}


$array = array(
  "idnumber" => array("123456"),
  "names" => array("name1", "name2"),
  "keycodes" => array(101, 102, 103)
);

$result = crossProduct($array["idnumber"], $array["names"], $array["keycodes"]);

结果:

Array
(
    [0] => Array
        (
            [0] => 123456
            [1] => name1
            [2] => 101
        )

    [1] => Array
        (
            [0] => 123456
            [1] => name1
            [2] => 102
        )

    [2] => Array
        (
            [0] => 123456
            [1] => name1
            [2] => 103
        )

    [3] => Array
        (
            [0] => 123456
            [1] => name2
            [2] => 101
        )

    [4] => Array
        (
            [0] => 123456
            [1] => name2
            [2] => 102
        )

    [5] => Array
        (
            [0] => 123456
            [1] => name2
            [2] => 103
        )

)