避免未定义的偏移误差

时间:2016-01-22 10:01:53

标签: php arrays iterator

我有以下功能

for (int j=0; j < shortDNA.length(); j++)
    {
        currentCharLong=longDNA.charAt(a)+ "";
        currentCharShort=shortDNA.charAt(j)+ ""; 

        if ( (currentCharShort.equalsIgnoreCase("a") && currentCharLong.equalsIgnoreCase("t"))||
            (currentCharShort.equalsIgnoreCase("t") && currentCharLong.equalsIgnoreCase("a"))||
            (currentCharShort.equalsIgnoreCase("c") && currentCharLong.equalsIgnoreCase("g"))||
            (currentCharShort.equalsIgnoreCase("g") && currentCharLong.equalsIgnoreCase("c")) )
        {
            match +=1;
            a +=1;
        }
        else break;
    }

我正在使用它

function getSum($array){
    if(is_array($array)) {
        $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
        $sum = 0;
        foreach ($iterator as $key => $value) {
            $sum += $value;
        }
    } else{
        $sum = $array;
    }
    return $sum;
}

如何使用类似$teams = array(); $teams[1]['AREA I']['blue'] = 30; $teams[1]['AREA I']['green'] = 25; $teams[1]['AREA II']['blue'] = 15; $teams[2]['AREA I']['blue'] = 40; echo getSum($teams); //output: 110 echo getSum($teams[1]); //output: 70 echo getSum($teams[1]['AREA I']); //output: 55 echo getSum($teams[1]['AREA I']['blue']); //output: 30 (未设置密钥区域IV)时如何避免错误未定义偏移量?在这种情况下,我希望该函数返回零。

1 个答案:

答案 0 :(得分:1)

由于错误发生在调用 getSum 函数之前,因此无法更改该函数以使其起作用。

但是,如果您愿意更改传递给 getSum 的参数,则可以解决这个问题。您可以在没有其他密钥规范的情况下传递数组(以避免潜在的错误)并将密钥指定为第二个参数。然后将其留给 getSum 以尝试获取该值(如果存在),如下所示:

function getSum($array, $path = array()){
    // process second argument:
    foreach ($path as $key) {
        if (!is_array($array) || !isset($array[$key])) {
            return 0; // key does not exist, return 0
        }
        $array = $array[$key];
    }
    if(is_array($array)) {
        $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
        $sum = 0;
        foreach ($iterator as $key => $value) {
            $sum += $value;
        }
    } else{
        $sum = $array;
    }
    return $sum;
}

$teams = array();
$teams[1]['AREA I']['blue'] = 30;
$teams[1]['AREA I']['green'] = 25;
$teams[1]['AREA II']['blue'] = 15;
$teams[2]['AREA I']['blue'] = 40;

// pass an optional 2nd argument:    
echo getSum($teams); //output: 110
echo getSum($teams, [1]); //output: 70
echo getSum($teams, [1,'AREA I']); //output: 55
echo getSum($teams, [1,'AREA I','blue']); //output: 30
echo getSum($teams, [2, 'AREA IV']); // no error, output: 0