在递归迭代期间查找数组中的父键

时间:2013-11-18 21:07:50

标签: php arrays recursion

考虑像这样的数组结构

[DVTTISEGA] => Array
        (
            [attr] => Array
                (
                    [DepartureDateTime] => 2014-03-17T06:15:00
                    [ArrivalDateTime] => 2014-03-17T10:50:00
                    [RPH] => 1
                    [FlightNumber] => 4376
                    [ResBookDesigCode] => U
                    [NumberInParty] => 4
                    [Status] => 36
                    [E_TicketEligibility] => Eligible
                    [DepartureDay] => Mon
                    [Distance] => 6197
                    [DateChangeNbr] => 0
                )

            [DepartureAirport] => Array
                (
                    [attr] => Array
                        (
                            [LocationCode] => MRS
                            [CodeContext] => IATA
                            [Terminal] => MP2
                        )

                )

            [ArrivalAirport] => Array
                (
                    [attr] => Array
                        (
                            [LocationCode] => DKR
                            [CodeContext] => IATA
                        )

                )

            [OperatingAirline] => Array
                (
                    [value] => ML
                    [attr] => Array
                        (
                            [FlightNumber] => 4376
                        )

                )

            [Equipment] => Array
                (
                    [attr] => Array
                        (
                            [AirEquipType] => 735       
                        )

                )

        )

有两个LocationCode。一个内部父数组,其中键DepartureAirport和其他内部ArrivalAirport。我必须将LocationCode存储在单独的变量中,具体取决于父键。我用代码递归遍历数组:

function arrayTraverse($unserializedarray){
        foreach ($unserializedarray as $key => $value) {
            print "$key {\n";
                if(is_array($value)){
                    arrayTraverse($value);
                }
                else{
                    print "    $key => $value\n";
                }
            print "}\n";
        }
    }

现在在这段代码中,如何根据我提到的不同父键将LocationCode分配给不同的变量?

1 个答案:

答案 0 :(得分:0)

传递您在数组中的路径,该数组由所有键组成,作为您函数的第二个参数。 现在,您可以检查导致您获得当前值的键的历史记录。

function arrayTraverse( $unserializedarray, $path = array() ){
        foreach ($unserializedarray as $key => $value) {
            print "$key {\n";
                if(is_array($value)){
                    $path[] = $key;
                    arrayTraverse( $value, $path );
                }
                else{
                    print "    $key => $value\n";
                }
            print "}\n";
        }
    }

或者您可以在不遍历数组的情况下访问值:

$departureAirportCode = $unserializedarray[ 'DVTTISEGA' ][ 'DepartureAirport' ][ 'attr' ][ 'LocationCode' ];
$arrivalAirportCode = $unserializedarray[ 'DVTTISEGA' ][ 'ArrivalAirport' ][ 'attr' ][ 'LocationCode' ];