[英]PHP - Accessing Multidimensional Array Values
經過數小時的混亂,流汗和拔頭發,我仍然無法訪問這些值。 我想遍歷數組的第一級,這對於基本的'foreach'循環就足夠簡單了,但是我似乎無法進入第二個子數組上的'['suitability']'數組。 我環顧四周,但除了真正的基本數組教程外似乎什么也沒得到,而基本的數組教程似乎沒有深入研究循環。
我正在嘗試訪問嵌套/子數組中的值,即'['Species_name']'。
我不想使用關聯鍵,因為排序有點問題。
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
)
)
)
)
可能使您感到不適的是,適應性是一個數組數組,而不僅僅是一個數組,因此在示例中,您想要獲取第一個第二個頂級元素的species_name屬性,可以使用類似
$array[1]["suitability"][0]["species_name"];
值得注意的是,您的第一個數組不包含“適合性”值,因此將無法對其進行訪問。 在foreach循環中,您可以使用類似於以下的構造:
foreach($array as $value){
if (isset($value["suitability"])){
echo $value["suitability"][0]["species_name"];
}
}
您可以看一下PHP:RecursiveArrayIterator類
這使您可以迭代多個嵌套的ArrayIterator。 如果不使用任何ArrayIterator,則應考慮嘗試使用它們。
Iracicot的答案幫助我找到了使用RecursiveIterator類訪問遞歸數組的值的方法,如下所示。 根據http://php.net/manual/en/class.recursiveiteratoriterator.php,我的解決方案最終使用了更加有用的RecursiveIteratorIterator類。 請記住一個非常有用的事實,即最終產品是扁平陣列,我個人發現使用起來更容易。
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.