将1维数组升级为2维数组

时间:2017-03-04 13:19:03

标签: php arrays

我有一些代码可用于1维数组:

$colour_array = [
    "1" => "#9E2A2B",
    "2" => "#3E5C76",
    "3" => "#335C67",
];

$colour1 = $colour_array[$colourdata];
...

我希望能够在我的数组中为每个数字存储两种颜色,像这样我尝试了很多东西,按照以下方式:

$colour_array = [
    "1" => "#9E2A2B","#3E5C76",
    "2" => "#3E5C76","#3E5C76",
    "3" => "#335C67","#3E5C76",
];

$colour1 = $colour_array[$colourdata[1]];
$colour2 = $colour_array[$colourdata[2]];

但我真的不了解多维数组。

2 个答案:

答案 0 :(得分:2)

您可以在数组中创建数组:

$colour_array = array(
    "1" => array("#9E2A2B","#3E5C76"),
    "2" => array("#3E5C76", "#3E5C76"),
    "3" => array("#335C67", "#3E5C76")
);

或与关联的数组

$colour_array = array(
    "1" => array("red" => "#9E2A2B","bleu" => "#3E5C76"),
    "2" => array("green" => "#3E5C76", "orange" => "#3E5C76"),
    "3" => array("purple" => "#335C67","yellow" => "#3E5C76")
);

var_export($colour_array);

输出:

array (
  1 => 
  array (
    'red' => '#9E2A2B',
    'bleu' => '#3E5C76',
  ),
  2 => 
  array (
    'green' => '#3E5C76',
    'orange' => '#3E5C76',
  ),
  3 => 
  array (
    'purple' => '#335C67',
    'yellow' => '#3E5C76',
  ),
)

如果你想访问一些值,我会做一些像这样的事情:

echo $colour_array[1]['blue'];

输出:

  

#3E5C76

希望它有所帮助!

PS:此处的十六进制值与颜色名称不匹配。仅举例来说。

答案 1 :(得分:1)

请试试这个可能用于你的

$colour_array = [
        "1" => "#9E2A2B",
        "2" => "#3E5C76",
        "3" => "#335C67",
    ];
    foreach ($colour_array as $key => $color) {
        echo "<pre>"; print_r($color);
        $colour_array[$key] = array();
        array_push($colour_array[$key], $color);
        array_push($colour_array[$key], "#ffffff");

    }
    echo "<pre>"; print_r($colour_array);