PHP - 访问多维数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17139453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:21:21  来源:igfitidea点击:

PHP - Accessing Multidimensional Array Values

phparraysmultidimensional-array

提问by Paul Pavlou

After several hours of messing, sweating and pulling my hair out I'm still unable to access these values. I want to loop through the first level of arrays, and that's simple enough with a basic 'foreach' loop but I can't seem to get to the '['suitability']' array on the second sub array. I've looked around but can't seem to get anything other than really basic array tutorials which don't seem to delve to far into looping.

经过几个小时的混乱,出汗和拔头发后,我仍然无法访问这些值。我想遍历第一级数组,这对于基本的“foreach”循环来说已经足够简单了,但我似乎无法访问第二个子数组上的“['suitability']”数组。我环顾四周,但除了似乎没有深入研究循环的真正基本数组教程之外,似乎什么也找不到。

I'm trying to access the values in the nested/sub array ie '['Species_name']'.

我正在尝试访问嵌套/子数组中的值,即 '['Species_name']'。

I don't want to use associative keys as the sorting is a bit of an issue.

我不想使用关联键,因为排序有点问题。

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Bradeley Hall Pool
            [postcode] => CW1 5QN
            [lat] => 53.10213
            [lon] => -2.41069
            [size] => 1.60
            [pegs] => 21
            [distance] => 26.6
        )

    [1] => Array
        (
            [id] => 2
            [name] => Farm Pool
            [postcode] => CW9 6JQ
            [lat] => 53.320502
            [lon] => -2.549049
            [size] => 0.88
            [pegs] => 8
            [distance] => 15.4
            [suitability] => Array
                (
                    [0] => Array
                        (
                            [fk_water_id] => 2
                            [fk_species_id] => 4
                            [species_name] => Barbel
                            [species_rating] => 1
                            [record_id] => 1
                            [weight_kg] => 2.721554
                            [length_cm] => 40
                            [height_cm] => 30
                        )
                )
       )
)

回答by Orangepill

The thing that is probably tripping you up is that suitability is an array of arrays not just an array so in an example where you want to get the species_name property of the first second top level element you would use something like

可能让您感到困惑的是,适用性是一个数组数组,而不仅仅是一个数组,因此在您想要获取第一个第二个顶级元素的 species_name 属性的示例中,您可以使用类似的东西

$array[1]["suitability"][0]["species_name"];

It's worth noting that your first array does not contain a "suitability" value so that would not be able to be accessed. In a foreach loop you could use a construct similar to this:

值得注意的是,您的第一个数组不包含“适用性”值,因此无法访问。在 foreach 循环中,您可以使用与此类似的构造:

foreach($array as $value){
    if (isset($value["suitability"])){
        echo $value["suitability"][0]["species_name"];
    }
}

回答by lracicot

You may take a look at PHP: RecursiveArrayIterator class

你可以看看PHP: RecursiveArrayIterator class

This allow you to iterate over multiples nested ArrayIterator. If you're not using any ArrayIterator, then you should consider to try them.

这允许您迭代多个嵌套的 ArrayIterator。如果您没有使用任何 ArrayIterator,那么您应该考虑尝试使用它们。

回答by AnotherLongUsername

Iracicot's answer helped me find my way towards accessing the values of a recursive array using the RecursiveIterator class as below. My solution ended up using the even more useful RecursiveIteratorIterator class as per http://php.net/manual/en/class.recursiveiteratoriterator.php. Please bear in the mind the very useful fact that the end product is a flattened array which I personally found much easier to work with.

Iracicot 的回答帮助我找到了使用 RecursiveIterator 类访问递归数组值的方法,如下所示。我的解决方案最终使用了更有用的 RecursiveIteratorIterator 类,如http://php.net/manual/en/class.recursiveiteratoriterator.php。请记住一个非常有用的事实,即最终产品是一个扁平的阵列,我个人发现它更容易使用。

<table style="border:2px;">
  <tr>
    <th>Time</th>
    <th>Service Number</th>
    <th>Destination</th>
  </tr>
<?php 
foreach($stops as $buses){
       $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($buses));
       $bus = (iterator_to_array($iterator,true)); 
       print('<tr><td>'.$bus['AimedDepartureTime'].'</td><td>'.$bus['PublishedLineName'].'</td><td>'.$bus['DirectionName'].'</td></tr>');
}
?>
</table>

回答by Minwork

For getting nested element value from multidimensional array (with optional fallback to default value) you can use get methodfrom this array library:

从多维数组越来越嵌套元素值(可选退回到默认值),可以使用get方法该阵列库

Arr::get($array, "$index1.suitability.$index2.species_name")

// Or using array of keys
Arr::get($array, [$index1, 'suitability', $index2, 'species_name'])