循环数组内容值由单值和数组组成

时间:2015-12-04 05:05:54

标签: php arrays associative-array

我试图循环这个数组,但我仍然得到错误

我有一个这样的数组:

1 => ["name"=>"A", "related"=>[
["signal"=>"A1", "color"=>"green"],
["signal"=>"A2", "color"=>"lime"],
["signal"=>"A3","color"=>"yellowGreen"]
]] 
2 => ["name"=>"B", "related"=>[
["signal"=>"B1", "color"=>"Red"],
["signal"=>"B2", "color"=>"Pink"]
]]

如何显示为 - A:绿色,石灰色,黄色格里布                     - B:红色,粉红色

这是我尝试以上述格式显示的代码

foreach($arr as $key => $value){
  echo $value["name"];
  foreach($value["related"] as $k){
    echo $k["color"] . ",";
  }
}

抛出错误,这个数组没有$ value ["相关"]索引。但它可以回应$ value [" name"] ???

谢谢!

1 个答案:

答案 0 :(得分:0)

找到解决方案如下:

$array = [1 => [
    "name" => "A",
    "related" => [
        ["signal" => "A1", "color" => "green"],
        ["signal" => "A2", "color" => "lime"],
        ["signal" => "A3", "color" => "yellowGreen"]
    ]
],
    2 => ["name" => "B", "related" => [
        ["signal" => "B1", "color" => "Red"],
        ["signal" => "B2", "color" => "Pink"]
    ]]
];

foreach ($array as $ar) {
    $new_arr = array_column($ar['related'], 'color');
    $required_string = implode(', ', $new_arr);
    echo $ar['name'].' : ' .$required_string;
    echo "<br />";
}

对于PHP版本&lt; 5.5你可以使用以下解决方案:

foreach ($array as $ar) {
    $new_arr = array_map(function ($value) {
        return  $value['color'];
    }, $ar['related']);
    $required_string = implode(', ', $new_arr);
    echo $ar['name'].' : ' .$required_string;
    echo "<br />";
}

您可以在http://php.net/manual/en/control-structures.foreach.php

找到有关foreach循环的更多详细信息