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 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据