给出一个阵列,其中包含不同家用电器在工作日消耗的功率单元数量。您必须找到阵列中每个设备的总消耗量。结果数组应该是('REFRIGERATOR'=> 47,'WASHINGMACHINE'=> 29,...)
$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))
);
输出:数组([REFRIGERATOR] => 47 [WASHINGMACHINE] => 29 [OVEN] => 28 [TV] => 28 [FAN] => 26)
答案 0 :(得分:-2)
您的代码大多是正确的,只需要进行一些调整:
boolean isRooted;
@Override
protected void onCreate(Bundle savedInstanceState) {
isRooted=AndroidUtils.isDeviceRooted();
if (isRooted) {
Intent i = new Intent(this, ActivityB.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
finish();
}else{
....
// other code of onCreate()
}
}
请注意以下事项:
1)不要覆盖您正在使用的变量。我创建了一个新的$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);
}
}
数组,用于存储您想要的数据。
2)$ value实际上是消费值数组。使用array_sum获取该数组的总和,然后将其添加到相关的计数器中。
3)确保在添加索引之前创建索引,这样就不会出错。