foreach没有为web服务正确循环

时间:2014-09-21 12:42:06

标签: php arrays for-loop foreach

我有从网络服务生成的数组。

Array ( 
    [TPA_Extensions] => Array (
        [TPARoomDetail] => Array ( 
            [GuestCounts] => Array ( 
                [GuestCount] => Array ( 
                        [!AgeQualifyingCode] => 10 
                        [!Count] => 1
                ) 
            ) 
            [!Occupancy] => Single 
            [!OccupancyCode] => SGL 
        ) 
    ) 
    [!IsRoom] => true 
    [!Quantity] => 1 
    [!RoomType] => Palace Gold Club Room 
    [!RoomTypeCode] => PGC 
)

我的foreach循环如下

foreach ($roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"] as $guestcount) {

echo "guest count1->";print_r($guestcount);
echo "guest count2->";  print_r($roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"]);
}

我得到的输出是 客人

count1->10 guest count2->Array ( [!AgeQualifyingCode] => 10 [!Count] => 1 ) 

来宾count1应该是一个数组

Array ( [!AgeQualifyingCode] => 10 [!Count] => 1 )  but it comes as an int 10 ..

为什么会这样......?

2 个答案:

答案 0 :(得分:0)

您的输出正确无误, $guestcount 的数字为“10”,

其中 $roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"] 拿一个阵列。

这是你的循环:

foreach ($roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"] as $guestcount) {

  echo "guest count1->";print_r($guestcount);
  echo "guest count2->";  print_r($roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"]);
}

这个循环将运行2次,因为这是 GuestCount 数组中的子项数。 它将是'10',然后是'1',正好反映了阵列的结构:

[!AgeQualifyingCode] => 10 
[!Count] => 1

答案 1 :(得分:0)

由于第一个索引保存整数值而第二个索引保存数组,因此代码没有错误。但是,访问数组值的方法非常复杂,并且看起来不太好。您可以按照以下更有效的方式访问数组值和键。

1)创建一个方法,该方法获取您要访问的数组的路径

例如,根据您的代码,如果我想访问 AgeQualifyingCode 键,那么我必须编写$ roomType [" TPA_Extensions"] [" TPARoomDetail"] [" GuestCounts"] [" GuestCount"] [" AgeQualifyingCode&#34]。

这看起来不太好,如果您只需要传递要访问该值的密钥路径,那就太棒了。

例如:/ TPA_Extensions / TPARoomDetail / GuestCounts / GuestCount / AgeQualifyingCode

您只需定义一个获取键路径的函数,并返回该键的值

<?php

    function path($path=null){
        if($path){
            $array = $theNameOfOriginalArray
            $path  = explode('/',$path);

            foreach($path as $sub){
                if(isset($array[$sub])){
                    $array = $array[$sub];
                }
            }

            return $array;
        }
    }

    $value = path('TPA_Extensions/TPARoomDetail/GuestCounts/GuestCount/AgeQualifyingCode');
    //will return 10
?>