for循环多维数组

时间:2016-04-13 04:28:26

标签: php arrays multidimensional-array

所以我有2个阵列。

$ ARRAY1:

Array ( [maxwater] => 1 [maxfodder] => 2 [maxmob] => 3 [maxalt] => 4 [maxhum] => 5 [mintemp] => 6 )

第二个是多维数组:

Array

(     [0] =>排列         (             [0] => 2             [1] => 3             [2] => 4             [3] => 4             [4] => 1             [5] => 2         )

[1] => Array
    (
        [0] => 3
        [1] => 2
        [2] => 1
        [3] => 4
        [4] => 1
        [5] => 3
    )

[2] => Array
    (
        [0] => 4
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 1
        [5] => 3
    )

[3] => Array
    (
        [0] => 3
        [1] => 4
        [2] => 2
        [3] => 1
        [4] => 1
        [5] => 3
    )

[4] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 2
        [3] => 2
        [4] => 3
        [5] => 3
    )
)

我想在这里做的只是将$array1中的每个数字除以$array2中的每一列,例如$ array1 = 1将第1列(2 3 4 3 1)划分为$ array2,$ array1 = 2将第2列(3 2 1 4 2)分开,依此类推。

我已经尝试使用此代码了,这似乎是一个错误:

  

注意:未定义的偏移量:在第42行的C:\ xampp \ htdocs \ Livestockmapping \ dsssawprocess.php中为0   警告:在第42行的C:\ xampp \ htdocs \ Livestockmapping \ dsssawprocess.php中除以零       0   代码:

$yaxis = sizeof($array2);
$xaxis = max(array_map('count', $array2));

echo $xaxis;
echo $yaxis;

//normalization
for($i=0; $i < $xaxis; $i++)
{
    for($j=0; $j < $yaxis; $j++)
    {
        $c1norm = round($array2[$i][$j]/$array1[$j]);
        echo $c1norm;
    }
}

有人可以帮我找到正确的方法吗?

*编辑: 我尝试使用:

foreach($array1 as $v){
echo (array_sum(array_column($array2, $v - 1)) / $v) . "<br />";
}

看起来像这样的结果

Array
(
    [0] => 13
    [1] => 6
    [2] => 3.6666666666667
    [3] => 3.5
    [4] => 1.4
    [5] => 2.3333333333333
)

但我想要的是将array2中的每个值分开:

2 / 1 = 2
3 / 1 = 3
4 / 1 = 4
3 / 1 = 3
1 / 1 = 1


3 / 2 = 2
2 / 2 = 1
1 / 2 = 1
4 / 2 = 2
2 / 2 = 1


4 / 3 = 1
1 / 3 = 0
2 / 3 = 1
2 / 3 = 1
2 / 3 = 1

依旧......

2 个答案:

答案 0 :(得分:1)

现在,您要根据$array2矩阵划分元素。

包含for的{​​{1}}循环(每个$array1并将其应用于$array2的每一列

$array2[$j][$i] 
        ^ column first

示例:

// $array1 = array_values($array1); numeric index conversion
$c = count($array1);
$xaxis = sizeof($array2);
$yaxis = max(array_map('count', $array2));

// normalization
for($i = 0; $i < $c; $i++) {
    for($j = 0; $j < ($yaxis - 1); $j++) {
        $c1norm = round($array2[$j][$i] / $array1[$i]);
        echo $c1norm;
    }
}

Demo

答案 1 :(得分:0)

$indexLevelOne = count($array2);
$indexLevelTwo = count($array2[0]);

// normalization
$k=0;
foreach($array1 as $v){
    for($j=0; $j<$indexLevelTwo; $j++){
        if($j != $k) continue;
        for($i=0; $i<$indexLevelOne; $i++){
            $c1norm = round($array2[$i][$j] / $v);
            echo $array2[$i][$j] . " / " . $v . " = " . $c1norm, "\n";
        }
       echo "\n\n"; 

    }
    echo "\n\n";
    $k++;
}