将多维数组转换为单个数组

时间:2018-04-12 16:19:22

标签: php arrays multidimensional-array

尝试将此多维数组转换为单维数组。希望我所说的是描述它的最佳方式。我有一个完整的阵列,我需要缩短。

   $theme = array(
        "1" => array(
            "name" => "one",
            "color" => "red"
        ),
        "2" => array(
            "name" => "two",
            "color" => "green"
        ),
        "3" => array(
            "name" => "three",
            "color" => "pink"
        ),
        "4" => array(
            "name" => "four",
            "color" => "orange"
        ),
        "5" => array(
            "name" => "five",
            "color" => "blue"
        ),
        "6" => array(
            "name" => "six",
            "color" => "black"
        ),

    );

我想将其减少为:

 $theme = array("1"=>"red", "2"=>"green", "3"=>"pink", "4"=>"orange", "5"=>"blue", "6"=>"black");

1 个答案:

答案 0 :(得分:0)

您只需从color索引中提取值:

$theme = array_column($theme, 'color');

但那将从0开始。从1开始:

$theme = array_combine(range(1, count($theme)), array_column($theme, 'color'));

或者,如果您愿意,请提取color并按name索引:

$theme = array_column($theme, 'color', 'name');