SimpleXML对象数组仅返回PHP

时间:2015-12-30 11:03:12

标签: php simplexml

问题摘要

为什么SimpleXML对象数组只返回第一个值,而不是所有数组元素。

问题解释

XML结构(简化)

<states>
    <state>
        <name>California</name>
        <cities>
            <city>
                <name>LosAngeles</name>
            </city>
            <city>
                <name>SanFrancisco</name>
            </city>
        </cities>
    </state>
    <state>
        <name>Nevada</name>
        <cities>
            <city>
                <name>LasVegas</name>
            </city>
        </cities>
    </state>
</states>

方法(简化)

我的getCityList课程中有City方法:

public function getCityList( $givenState = false ){
    $records = array();
    $states = $this->states->state;

    [var_dump( $states->asXML() )]
    [var_dump( $states[0]->asXML() )]
    [var_dump( $states[1]->asXML() )]

    foreach( $states as $state ){
        if( empty( $givenState ) || ( $state->name == $givenState ) ){
            $cities = $state->cities->city;
            foreach( $cities as $city ){
                $records[ trim( $state->name ) ][] = trim( $city->name );   
            }
        }else{
            return false;   
        }
    }
    return $records;
}

对于$givenState = 'California'$givenState = 'Nevada'var_dump( $states->asXML() )给出:

<state>
    <name>California</name>
    <cities>
        <city>
            <name>LosAngeles</name>
        </city>
        <city>
            <name>SanFrancisco</name>
        </city>
    </cities>
</state>

var_dump( $states[0]->asXML() )给出:

<state>
    <name>California</name>
    <cities>
        <city>
            <name>LosAngeles</name>
        </city>
        <city>
            <name>SanFrancisco</name>
        </city>
    </cities>
</state>

var_dump( $states[1]->asXML() )给出:

<state>
    <name>Nevada</name>
    <cities>
        <city>
            <name>LasVegas</name>
        </city>
    </cities>
</state>

getCityList方法会在$givenState = 'California'false$givenState = 'Nevada'上返回正确的结果。

为什么这个数组有这种行为?

如何让它工作以便还返回Nevada个结果?

1 个答案:

答案 0 :(得分:1)

return false; if中的第一次不匹配后,您正在foreach( $states as $state ),如果您在第二次检查时遇到错误,则需要删除return false并让循环检查所有项目并在结束外部循环返回$recordsfalse,如此

....
if( empty($givenState){
    return false;
}

foreach( $states as $state ){
    if( $state->name == $givenState ){
        $cities = $state->cities->city;
        foreach( $cities as $city ){
            $records[ trim( $state->name ) ][] = trim( $city->name );   
        }
    }
}

return count($records) ? $records:false;

我也将empty($givenState)移到了循环

之上