在 php 中排序并获取数组中值的频率?

Sorting and getting the frequency of values in an array in php?

我有一个包含字段标题列表的 xml 文件。我想将它们存储在一个数组中,然后按字母顺序对它们进行排序,然后 "title" 出现最多。我的实际 XML 文件太大,无法复制到此处(PS:我正在从一堆 XML 文件中导入)。

简而言之,这是 XML 文件的外观示例。

<add overwrite="true">
<docs>

    <field name="id">9637a08df6aa0765</field>
    <field name="url">http://somewebsite.ca </field>
    <field name="blogurl">http://www.someblog.com</field>
    <field name="published">2015-05-21</field>
    <field name="language">English</field>
    <field name="title">Stephen Harper</field>
    <field name="title">Mike Duffy Trial</field>
    <field name="title">POTUS on Twitter</field>
    <field name="title">Tim Hortons Closed</field>
    <field name="title">Stephen Harper</field>
    <field name="title">The New iPhone</field>
    <field name="title">Stephen Harper</field>
</docs>
</add>

假设我从 XML 文件中获取 title 属性并将它们存储在一个数组中。然后我想按字母顺序对该数组排序,然后按 "titles" 的频率排序。

这就是我目前所拥有的。

<?php

    $titles_array = array();
    $counter = 0; 
    $xml = simplexml_load_file("fields.xml") or die ("Error: Cannot Create Object");

    foreach($xml->docs->field as $fields){
        array_push ($titles_array, $fields);
        echo $fields . "<br>";
        $counter++;  
    }

    echo '<p>' . "Sorted Array" . '</p>';

    sort($titles_array);

    for ($a=0; $a<$counter; $a++){  
        echo $titles_array[$a] . "<br>";
    }

?>

输出居然不是按字母顺序排列的? 另外,我如何才能显示最频繁的 "title"?

您的 $fields 实际上将成为您的 foreach 循环内的整个 SimpleXMLElement。如果您改用它,您的数组将按预期排序:

array_push($titles_array, (string)$fields);

要计算出现次数,创建另一个数组:

$titles_count = array();

然后在你的循环中,做这样的事情:

if (isset($titles_count[(string)$fields])) {
  $titles_count[(string)$fields] = $titles_count[(string)$fields] + 1;
} else {
  $titles_count[(string)$fields] = 1;
}

最后,像这样得到你的最高计数的钥匙:

echo array_search(max($titles_count), $titles_count);

像这样将所有代码放在一起:

<?php

    $titles_array = array();
    $titles_count = array();
    $xml = simplexml_load_file("fields.xml") or die ("Error: Cannot Create Object");

    foreach($xml->docs->field as $fields){
      array_push ($titles_array, (string)$fields);
      echo $fields . "<br>";

      // First we check if the key exists.
      // Example $titles_count['Tim Hortons Closed']
      if (isset($titles_count[(string)$fields])) {
        // If it does, augment the count by 1;
        $titles_count[(string)$fields] = $titles_count[(string)$fields] + 1;
      } else {
        // If it doesn't yet, set the count to 1;
        $titles_count[(string)$fields] = 1;
      }
    }

    echo "<p>Sorted Array</p>";

    sort($titles_array);

    for ($a=0; $a<$counter; $a++){  
      // Let's put the count in for each one:
      echo $titles_array[$a] . "(" . $titles_count[$titles_array[$a]] . ")" . "<br>";
    }

    echo "<p>Highest key count:</p>";

    // Here we get the value with the highest count use max(...)
    // Then we get it's key (example 'Tim Hortons Closed')
    echo array_search(max($titles_count), $titles_count);

?>