我需要一个返回两列值的除法结果的函数?

时间:2018-01-15 22:50:13

标签: php arrays

所以我有这个数组输出:

    [period5] => Array
        (
            [SI] => 0
            [B K] => 0
            [FS] => 0
            [DD] => 3
            [score_counter_SI] => 0
            [score_counter_B K] => 0
            [score_counter_FS] => 0
            [score_counter_DD] => 1
        )
    [period6] => Array
        (
            [SI] => 6
            [B K] => 0
            [FS] => 0
            [DD] => 0
            [score_counter_SI] => 2
            [score_counter_B K] => 0
            [score_counter_FS] => 0
            [score_counter_DD] => 0
        )
etc

我需要为Google输出JS,其中单引号之间的值只是数字的字符串表示(我得到除以零的错误,我不需要{{1}在输出中)

score_counter_xx

所以我需要($ key [0] / $ key [4]),($ key [1] / $ key [5]),($ key [2] / $ key [6])的结果,($ key [3] / $ key [7])

我现在拥有的php循环:

['period5', 0, '0', 0, '0', 0, '0', 3, '3'],
['period6', 3, '3', 0 '0', 0, '0', 0, '0'], 

但是所有的部门都是空白的?

1 个答案:

答案 0 :(得分:2)

没有$value[$key]$value是一个数字,而不是数组。您应该在那里使用$value,并使用$values['score_counter_'.$key]作为要分割的元素。您还忘记了该密钥中的_

不是通过连接字符串来构造JSON数组,而是使用json_encode()

$return = array();
foreach($inputArray as $period =>$values) {
   $temp = array($period);
   foreach($values as $key => $value) {
        $other_key = 'score_counter_'.$key;
        if (isset($values[$other_key]) && $values[$other_key] > 0) // prevent divide by 0
            $quotient = $value / $values[$other_key];
        } else {
            $quotient = 0;
        }
        array_push($temp, $quotient, (string)$quotient);
    }
    $return[] = $temp;
}
echo json_encode($return);