如何将数组作为可选参数传递并迭代它?

时间:2018-02-28 10:38:53

标签: php phpgraphlib

我正在尝试修改phpgraphlib,以便在使用多个条形颜色时生成图例。我在generateLegend()中添加了一个带颜色的数组作为可选参数,但它似乎不起作用。我不知道什么是错的。我以前没有PHP的经验,但在我看来,传递一个数组作为可选参数必须是可能的 这是我的代码:

protected function generateLegend(array $colors = array())
{
    // here is some code        
    if($this->bool_multi_color_bars) {
        // gets here
        if (!empty($colors)) {
            // doesn't get here
            $index = 0;
            foreach($colors as $key => $item) {
                // here is some code that creates the colored boxes
                $index++;
            }
        }
    }
}

这是调用函数的代码:

$colors = array();
foreach($data as $key => $value) {
    if($value < 3) {
        $colors[$key] = 'green';
    }
    elseif($value < 8) {
        $colors[$key] = 'orange';
    }
    else {
        $colors[$key] = 'red';
    }
}
$graph->setBarColors($colors);
$graph->setLegend(true, $colors);
$graph->createGraph();

编辑:使用以下代码调用generateLegend():

if ($this->bool_legend) { 
            $this->generateLegend(); 
        }

为了便于阅读,我遗漏了大部分代码,但我可以看到该方法被调用(因此我添加了代码所在的注释而不是)

1 个答案:

答案 0 :(得分:0)

我不确定,你真正想要的是什么。您目前看到的是empty的预期行为。没有元素的数组为空。

var_dump(empty([])); // true

如果要测试,如果实际设置了可选参数,则可以使用func_num_args

if (func_num_args() > 0) {
    // $colors was set
}

或使用其他默认参数并针对该类型进行测试。

function foo(array $bar = null) {
    if ($bar === null) {
        // ...
    }
}
相关问题