所有子键的PHP回声值

时间:2018-09-17 21:07:15

标签: php arrays

在以下数组中:

"options": {
                    "front-electric": {
                        "pt": "Vidros Eléctricos dianteiros",
                        "en": "Front electric"
                    },
                    "electric-diant-back": {
                        "pt": "Vidros Eléctricos diant. + trase.",
                        "en": "Electric diant. + Back."
                    },
                    "darkened": {
                        "pt": "Vidros Escurecidos",
                        "en": "Darkened"
                    },
                    "soundproofing-and-athermic": {
                        "pt": "Vidros Insonorizantes e Atérmicos",
                        "en": "Soundproofing and Athermic"
                    }
                }

我如何从“选项”数组中回显所有子键的值“ pt”

我可以尝试类似于['options'] ['pt']的东西,但是我不明白如何引用子键“ front-electric”,“ electric-diant-back” ...来自“选项”,它们都有不同的文本。

5 个答案:

答案 0 :(得分:1)

在我看来,这更像是json字符串。如果是这样,您将必须首先json_decode,然后遍历输出的数组。

foreach($array['options'] as $key => $value) 
{ 
    echo $value['pt']."<br>"; 
}

答案 1 :(得分:1)

假设您来自json_decode()

$options = [
  "front-electric" => [
      "pt" => "Vidros Eléctricos dianteiros",
      "en" => "Front electric"
  ],
  "electric-diant-back" => [
      "pt" => "Vidros Eléctricos diant. + trase.",
      "en" => "Electric diant. + Back."
  ],
  "darkened" => [
      "pt" => "Vidros Escurecidos",
      "en" => "Darkened"
  ],
  "soundproofing-and-athermic" => [
      "pt" => "Vidros Insonorizantes e Atérmicos",
      "en" => "Soundproofing and Athermic"
  ]
];

然后简单地做:$output = array_column($options, 'pt');将为您提供所需的数组。

在您的用例中检查这个小提琴:https://repl.it/repls/DefinitiveWavyProblem

答案 2 :(得分:1)

最好使用built-in functions之一,而不是循环。更简洁,更短的代码,可能会更高效。

array_walk($data, function($v, $k) {echo "$v[pt]\n";});

答案 3 :(得分:0)

您可以使用foreach循环(如@Jeff所述)

foreach($array['options'] as $key => $val){
    echo $val['pt'];
}

答案 4 :(得分:0)

尝试一下

$json = '{"options": {
            "front-electric": {
                "pt": "Vidros Eléctricos dianteiros",
                "en": "Front electric"
            },
            "electric-diant-back": {
                "pt": "Vidros Eléctricos diant. + trase.",
                "en": "Electric diant. + Back."
            },
            "darkened": {
                "pt": "Vidros Escurecidos",
                "en": "Darkened"
            },
            "soundproofing-and-athermic": {
                "pt": "Vidros Insonorizantes e Atérmicos",
                "en": "Soundproofing and Athermic"
            }
        }}';
$json_array = json_decode($json,true);  

foreach($json_array as $key=>$values){

    foreach($values as $subkeys=>$subvalues){

        print $subvalues['pt'] . "<br/>";   

    }

}

输出

VidrosEléctricosdianteiros
VidrosEléctricosdiant。 +交易。
Vidros Escurecidos
Vidros Insonorizantes eAtérmicos