0
<!DOCTYPE html>
<html>
    <head>
        <title>new Page</title>
    </head>
    <body>
        <?php
            $consumption = array( 'MONDAY' => array('REFRIGERATOR' => array(3, 9,    7), 'WASHINGMACHINE' => array(2, 4, 2, 8)), 'TUESDAY' => array('REFRIGERATOR' => array(5, 3, 8), 'OVEN' => array(4, 1, 4)), 'WEDNESDAY' => array('TV' => array(6, 9), 'REFRIGERATOR' => array(2, 3, 5, 2)), 'THURSDAY' => array('TV' => array(5, 3, 3, 2), 'FAN' => array(4, 9, 8, 5)), 'FRIDAY' => array('WASHINGMACHINE' => array(8, 5), 'OVEN' => array(3, 9, 7)) );
            $data = array();
            foreach ($consumption as $k=>$subArray) {
                foreach ($subArray as $id=>$value) {
                    if(!isset($data[$id])) {
                        $data[$id] = 0;
                    }
                    $data[$id]+=array_sum($value); 
                }
            }
        ?>
    </body>
</html>

代码似乎有什么问题?我得到一个空白页。预期的输出是

输出模型:array('REFRIGERATOR' =>47 'WASHINGMACHINE' =>29 'OVEN' =>28 'TV' =>28 'FAN' =>26)

4

1 回答 1

0

因为您只是在初始化data而从不打印它。获取print_r数组元素

<!DOCTYPE html>
<html>
    <head>
        <title>new Page</title>
    </head>
    <body>
        <?php
            $consumption = array( 'MONDAY' => array('REFRIGERATOR' => array(3, 9,    7), 'WASHINGMACHINE' => array(2, 4, 2, 8)), 'TUESDAY' => array('REFRIGERATOR' => array(5, 3, 8), 'OVEN' => array(4, 1, 4)), 'WEDNESDAY' => array('TV' => array(6, 9), 'REFRIGERATOR' => array(2, 3, 5, 2)), 'THURSDAY' => array('TV' => array(5, 3, 3, 2), 'FAN' => array(4, 9, 8, 5)), 'FRIDAY' => array('WASHINGMACHINE' => array(8, 5), 'OVEN' => array(3, 9, 7)) );
            $data = array();
            foreach ($consumption as $k=>$subArray) {
                foreach ($subArray as $id=>$value) {
                    if(!isset($data[$id])) {
                        $data[$id] = 0;
                    }
                    $data[$id]+=array_sum($value); 
                }
            }
            echo "Output model :";
            print_r($data);
        ?>
    </body>
</html>
于 2017-07-16T08:58:04.477 回答