根据特定数字划分数组中的元素

Dividing elements in arrays on specific numbers

我有 N 个这样的数组(例如 4 个,但数量可以不同)

k1 = [1,0,0,0,1,0,1]

k2 = [0,1,1,0,1,0,1]

k3 = [1,0,0,0,1,0,0]

k4 = [0,0,0,0,1,1,1]

我需要获取以下数组:

k1 = [0.5,0,0,0,0.25,0,0.33]

k2 = [0, 1,1,0,0.25,0,0.33]

k3 = [0.5,0,0,0,0.25,0,0]

k4 = [0, 0,0,0,0.25,1,0.33]

想法是根据其他数组中同一索引出现“1”的次数来划分每个元素。所以你总是得到 1 作为 k1[i]+k2[i]+k3[i]+k4[i]+...kn[i]

您必须用所有元素的总和创建一个新数组,然后像这样划分: 必须有一种“更清洁”的方法来做到这一点,但这行得通:

$k1 = [1,0,0,0,1,0,1];

$k2 = [0,1,1,0,1,0,1];

$k3 = [1,0,0,0,1,0,0];

$k4 = [0,0,0,0,1,1,1];

//we create an array with names of n array, i took 4 just to test it but it will works with n
$name=[];
for ($v = 1; $v <= 4; $v++) {
    $name[$v]="k".$v;
}

$sum=[0,0,0,0,0,0,0];

for ($k = 0; $k <= 6; $k++) {
    for ($j = 1; $j <= 4; $j++) {
        $sum[$k]=$sum[$k]+${$name[$j]}[$k];
    }
}

//and now we update 

for ($l = 0; $l <= 6; $l++) {
    if($sum[$l]!==0){
        for ($q = 1; $q <= 4; $q++) {       
            ${$name[$q]}[$l]=${$name[$q]}[$l]/$sum[$l];
        }
    }
}

//display to test
for ($m = 0; $m <= 6; $m++) {
    echo $k1[$m];
    echo " | ";
}