PHP

时间:2016-03-03 17:53:50

标签: php

好吧,我有点迷路了。这是我的代码,但是如何摆脱PHP错误,告诉我它是非法的偏移类型?我试图在颜色中循环。

$color = array(

    [0]=>"red", 
    [1]=>"cherry",
    [2]=>"orange",
    [3]=>"amber",
    [4]=>"blue",
    [5]=>"sapphire",
    [6]=>"green",
    [7]=>"forest green",
    [8]=>"purple",
    [9]=>"lavender");
 //starts at index 0

for($colorCount=0; $colorCount <=9; $colorCount++){

    if ($colorCount == 9){
        break;
    }
    echo implode(", ", $color).", ";

}

2 个答案:

答案 0 :(得分:1)

我认为可能会发生的事情是,因为PHP现在支持[]的短数组表示法。它将[0]解析为array(0),然后您尝试将其用作数组中的键,这是不允许的。这将解释确切的错误消息。

声明你的数组:

$color = array(
    0 => "red", 
    1 => "cherry",
    2 => "orange",
    3 => "amber",
    4 => "blue",
    5 => "sapphire",
    6 => "green",
    7 => "forest green",
    8 => "purple",
    9 => "lavender"
);

你甚至可以不用数字来做:

$color = array(
    "red", 
    "cherry",
    "orange",
    "amber",
    "blue",
    "sapphire",
    "green",
    "forest green",
    "purple",
    "lavender"
);

答案 1 :(得分:1)

$color = array(

        '0'=>"red", 
        '1'=>"cherry",
        '2'=>"orange",
        '3'=>"amber",
        '4'=>"blue",
        '5'=>"sapphire",
        '6'=>"green",
        '7'=>"forest green",
        '8'=>"purple",
        '9'=>"lavender"
        );
foreach ($color as $key => $res) {
       print_r($res);
}