使用foreach PHP的“通配符”键

时间:2017-04-02 13:21:37

标签: php arrays multidimensional-array

好的,所以我有一个看起来像这样的数组:

$array = ["person1" => ["person2" => ["something", "something else", "something else again"], "person3" => ["hey", "hi", "hello"]], "person4" => ["person5" => ["bob", "bill", "bobby", "billy"], "person6" => ["there", "their", "here"]]]

或者,在其他“词汇”中

$array = Array(
    "person1" => Array(
        "person2" => Array(
            "something", "something else", "something else again"),
        "person3" => Array(
            "hey", "hi", "hello")
    ),
    "person4" => Array(
        "person5" => Array(
            "bob", "bill", "bobby", "billy"),
        "person6" => Array(
            "there", "their", "here")
    )
); 

我有一个foreach循环,如下所示:

foreach($array["person1"] as $value){
}

我想进入数组的第三级(所有单词都像“某事”一样),但是有一个我不知道的方式的键(“person2”或“person3”) 我可以用一种“通配符”作为关键吗? (比如$array["person1"][wildcard][0]

1 个答案:

答案 0 :(得分:1)

没有"通配符"对于数组键,因为键是标识符。

只需遍历数组并回显第一个元素:

foreach ($array['person1'] as $key => $items) {
    // $key will contain the key, if you would need it.
    // $items contains the array of each child
    echo $items[0] . '<br />';
}
相关问题