@King_Of_Demons
Junior C# Developer

Как отсортировать XML файл по году через PHP?

Надо вывести данные из XML файла и отсортировать по году, в порядке возростания. Вывод данных сделал а вот сортировку не получается сделать. Пробовал через DOM но нечего толкого так и не выходит. Помогите пожалуйста с сортировкой.
Пример XML:
<catalog>
	<cd>
		<title>Empire Burlesque</title>
		<artist>Bob Dylan</artist>
		<country>USA</country>
		<company>Columbia</company>
		<price>10.90</price>
		<year>1985</year>
	</cd>
	<cd>
		<title>Hide your heart</title>
		<artist>Bonnie Tyler</artist>
		<country>UK</country>
		<company>CBS Records</company>
		<price>9.90</price>
		<year>1988</year>
	</cd>
</catalog>

PHP код:
<?php
$xml = simplexml_load_file("cdcatalog1.xml");
echo "<h2>".$xml->attributes()->name." ".$xml->attributes()->Date."</h2><br />";
echo '<table border="1px" cellpadding="1" color="black">
        <thead>
        <tr>
        <div>
            <th> Title </th>
            <th> Artist </th>
            <th> Country </th>
            <th> Company </th>
            <th> Price </th>
            <th> Year </th>
            </div>
        </tr>
        </thead>
        <tbody>';

foreach ($xml->children() as $item)
{
        echo "<tr>
<div>
            <td> $item->title </td>
            <td> $item->artist </td>
            <td> $item->country </td>
            <td> $item->company </td>
            <td> $item->price </td>
            <td> $item->year </td>
            </div>
          </tr>";
}
echo '</tbody></table>';
  • Вопрос задан
  • 190 просмотров
Решения вопроса 1
@King_Of_Demons Автор вопроса
Junior C# Developer
<?php
$cd = array();
$xml = simplexml_load_file('cdcatalog1.xml');
foreach($xml->children() as $item)
{
    $cd[] = array(
        'title'             => (string)$item->title,
        'artist'          => (string)$item->artist,
        'country'           => (string)$item->country,
        'company'         => (string)$item->company,
        'price' => (string)$item->price,
        'year' => (string)$item->year
    );
}


array_sort_by_column($cd, 'year');

var_dump($cd);

function array_sort_by_column(&$array, $column, $direction = SORT_ASC) {
    $reference_array = array();

    foreach($array as $key => $row) {
        $reference_array[$key] = $row[$column];
    }

    array_multisort($reference_array, $direction, $array);
}
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
JaxAdam
@JaxAdam
Junior Full-Stack Developer
/* Берем контент файла */
        $xmlString = file_get_contents($xmlFilePath);
        // Преобразуем xml в массив
        $xml = json_decode(
            json_encode((array)simplexml_load_string($xmlString)), true
        );

+ Пример сортировки из другого форума:
$data = array(
    array(
        "title" => "Another title",
        "date"  => "Fri, 17 Jun 2011 08:55:57 +0200"
    ),
    array(
        "title" => "My title",
        "date"  => "Mon, 16 Jun 2010 06:55:57 +0200"
    )
);

function sortFunction( $a, $b ) {
    return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
YCLIENTS Москва
от 200 000 до 350 000 ₽
Ведисофт Екатеринбург
от 25 000 ₽
ИТЦ Аусферр Магнитогорск
от 100 000 до 160 000 ₽