duanpo8329 2015-04-20 18:23
浏览 32
已采纳

Alpha按照SimpleXMLElement文档中的值对数组进行排序

I am pulling in a list of cities from sba.gov's API. Using SimpleXML I have the following bit of code:

$city_url = 'http://api.sba.gov/geodata/city_links_for_state_of/ca.xml';
    $city_xml = simplexml_load_file($city_url) or die("feed not loading");      
    $city_array = array();

    foreach($city_xml as $city) {
        $city_array[] = $city->name;
    }
    //sort($city_array);
    //usort($city_array, function($a, $b){ return strcmp($a["name"], $b["name"]); });
    print_r($city_array);

The XML format looks like this:

<sites count="431">
<site>
<county_name>Monterey</county_name>
<description nil="true"/>
<feat_class>Populated Place</feat_class>
<feature_id>1536</feature_id>
<fips_class>C1</fips_class>
<fips_county_cd>53</fips_county_cd>
<full_county_name>Monterey County</full_county_name>
<link_title nil="true"/>
<url>http://www.ci.marina.ca.us/</url>
<name>Marina</name>
<primary_latitude>36.68</primary_latitude>
<primary_longitude>-121.8</primary_longitude>
<state_abbreviation>CA</state_abbreviation>
<state_name>California</state_name>
</site>
<site>
<county_name>Contra Costa</county_name>
<description nil="true"/>
<feat_class>Populated Place</feat_class>
<feature_id>1537</feature_id>
<fips_class>C1</fips_class>
<fips_county_cd>13</fips_county_cd>
<full_county_name>Contra Costa County</full_county_name>
<link_title nil="true"/>
<url>http://www.cityofmartinez.org/</url>
<name>Martinez</name>
<primary_latitude>38.01</primary_latitude>
<primary_longitude>-122.13</primary_longitude>
<state_abbreviation>CA</state_abbreviation>
<state_name>California</state_name>
</site>
</sites>

I am trying to create an array from the XML and then sort the array by the name element so that I can output a form drop-down in alpha order.

Thank you for you time!

  • 写回答

1条回答 默认 最新

  • dongliu8559 2015-04-20 19:36
    关注

    the problem is that you're building and array of SimpleXMLElement Object instead of sortable strings. To solve your problem simply cast them when adding elements to the array:

    $city_array[] = (string) $city->name;
    

    Working example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败