假设我有一个这样的数组:
$arr_sequences =
array('00-02', '02-03', '03-07', '23-03', '03-23', '07-11', '11-10', '11-11');如何对数组进行排序,使值如下所示:
$arr_sequences =
array('00-02', '02-03', '03-23', '23-03', '03-07', '07-11', '11-11', '11-10');如果我们仔细观察,每个值都有一个id (代码),该id(代码)除以-
例如:
$arr_sequences[2] = '03-07'; // '07' as last code, then search another value with '07' in front of the value则下一个索引值应为
$arr_sequences[5] = '07-11'; // '07' front, then search '11' as next value目标是在不丢失任何长度的情况下对数组进行排序。
我试过树形算法,但我不能让它工作。
发布于 2013-07-15 20:32:52
一种暴力的方式,在php中。(未测试):
<?php
$arr = array('00-02', '02-03', '03-07', '23-03', '03-23', '07-11', '11-10', '11-11');
function findMatches($i, $val_ignore, $arr) {
$arr_matches = array();
foreach($arr as $key => $val) {
$j = substr_replace($val, '', 2);
if (($i == $j) && ($val != $val_ignore))
$arr_matches[] = $val;
}
return $arr_matches;
}
$arr_sorted = array();
foreach($arr as $key => $val) {
$i = substr_replace($val, '', 0, 3);
if (!in_array($val, $arr_sorted)) $arr_sorted[] = $val;
$arr_sorted = array_merge($arr_sorted, findMatches($i, $val, $arr));
}
?>https://stackoverflow.com/questions/17653470
复制相似问题