我有一个关联数组,其中包含日期键和团队值。例如:
- 2016 年 3 月 21 日 10:05 => '底特律 vs. 费城'
- 2016 年 3 月 21 日 7:05 =>'多伦多 vs. 渥太华'
- 2016 年 3 月 21 日 7:05 => 'Anahiem vs. Boston'
- 2016 年 3 月 21 日 10:25 => '芝加哥 vs. 温尼伯'
问题是我正在解析的 RSS 提要没有按顺序给我这些数据。所以我需要按日期对这些游戏进行排序,当我将这些字段添加到关联数组中时,重复的日期(你可以看到两个游戏在 3 月 21 日的 7:05 开始)被省略,因为两个键不能相同.我试图反转数据,以便键是值,值是键,我可以这样排序,但是当翻转数组时,(array_flip($input);) 出现同样的问题,因为再次两个键不能相同。
我确信有一个简单的方法来处理这个问题,但我在原地打转。
非常感谢任何帮助。
<?php
foreach ($feed->get_items() as $item): // this is my feed parser
$string = $item->get_title(); // gets each element
preg_match_all('/\((.*?)\)/', $string, $out);
$timedate = ($out[1][2]);
$array[$timedate] = $string; // creates an array with date as key, string data as values
endforeach;
?>
最佳答案
要执行您想要的操作,您必须将您拥有的数据放入一个稍微复杂的数组中,然后使用 usort()
函数根据您想要的键对其进行排序对其进行排序。这是一个例子:
<?php
// Multidimensional array of 'games'
$games[] = array('date' => 'March 21, 2016 10:05',
'title' => 'Detroit vs Philly');
$games[] = array('date' => 'March 21, 2016 7:05',
'title' => 'Toronto vs Ottawa');
$games[] = array('date' => 'March 21, 2016 7:05',
'title' => 'Anaheim vs Boston');
$games[] = array('date' => 'March 21, 2016 10:25',
'title' => 'Chicago vs Winnipeg');
// Define a custom sort function to sort based on
// the date index. This will not sort properly
// since I'm only using strcmp, but it works as
// an illustration. For more details see:
// http://php.net/manual/en/function.usort.php
function cmp($a, $b)
{
return strcmp($a['date'], $b['date']);
}
// Sort the array
usort($games, "cmp");
print_r($games);
这将产生以下排序数组:
Array
(
[0] => Array
(
[date] => March 21, 2016 10:05
[title] => Detroit vs Philly
)
[1] => Array
(
[date] => March 21, 2016 10:25
[title] => Chicago vs Winnipeg
)
[2] => Array
(
[date] => March 21, 2016 7:05
[title] => Toronto vs Ottawa
)
[3] => Array
(
[date] => March 21, 2016 7:05
[title] => Anaheim vs Boston
)
)
您会注意到日期没有完全正确排序,因为 strcmp()
只是在进行基本的字符串比较。您可以向我们定义的 cmp()
函数添加更多功能,以将字符串转换为 php 日期,然后对它们进行实际的日期比较。
关于php - 排序 PHP 数组,保留重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36144875/