У меня есть 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>
Так что скажем, я получаю атрибут title из файла XML и сохраняю его в массиве. Затем я хочу отсортировать этот массив в алфавитном порядке, а затем по частоте "заголовков".
Это то, что у меня есть до сих пор.
<?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>";
}
?>
Выход на самом деле не в алфавитном порядке? Кроме того, как мне показать наиболее частый "титул"?
Ваши $fields
самом деле будут целым SimpleXMLElement
внутри вашего цикла foreach. Ваши массивы будут сортироваться так, как ожидалось, если вы используете это:
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 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 key (example 'Tim Hortons Closed')
echo array_search(max($titles_count), $titles_count);
?>