为什么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
个结果?
答案 0 :(得分:1)
您return false;
if
中的第一次不匹配后,您正在foreach( $states as $state )
,如果您在第二次检查时遇到错误,则需要删除return false
并让循环检查所有项目并在结束外部循环返回$records
或false
,如此
....
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)
移到了循环