我有一个需要排序的数组,我将发布一个示例以便更好地理解。 这是我未分类的数组:
[0] => Array
(
[title] => This is some title
[catid] => 1
)
[1] => Array
(
[title] => This is some title
[catid] => 1
)
[2] => Array
(
[title] => This is some title
[catid] => 2
)
[3] => Array
(
[title] => This is some title
[catid] => 2
)
我需要像这样重新排序:
[0] => Array
(
[title] => This is some title
[catid] => 1
)
[1] => Array
(
[title] => This is some title
[catid] => 2
)
[2] => Array
(
[title] => This is some title
[catid] => 1
)
[3] => Array
(
[title] => This is some title
[catid] => 2
)
我将有更多这两个类别,我需要为每个类别选择一个项目,所以如果我有3个类别,那么我的catid就会像这样排序:
catid: 1,2,3,1,2,3
由于
答案 0 :(得分:4)
这是我的看法:
/** just generating some data, not part of script **/
$originalArray = array();
$title = range('a','z');
for ($x=0;$x<20;$x++) {
shuffle($title);
$originalArray[] = array(
'title' => implode(array_slice($title,0,rand(4,9))),
'catid' => rand(1,3)
);
}
/** end generating data **/
$tempArray = array();
foreach ($originalArray as $array) {
$tempArray[$array['catid']][] = $array['title'];
}
ksort($tempArray);
$newArray = array();
while (count($tempArray)>0) {
foreach ($tempArray as $mKey => &$mArray) {
if (count($mArray)>0)
$newArray[] = array('title'=>array_shift($mArray),'catid'=>$mKey);
}
$tempArray = array_filter($tempArray);
}
答案 1 :(得分:2)
这就是我提出的一维数组,但它也适用于2d。
$array = [1, 2, 2, 1, 3, 2, 3, 2, 1];
sort($array);
$newarray;
do{
$max= max($array);
for($a = 0; $a <= $max; $a++){
foreach($array as $key => $value){
if($value == $a){
$newarray[] = $value;
unset($array[$key]);
break;
}
}
}
}while(!empty($array));
此
1, 2, 2, 1, 3, 2, 3, 2, 1
会变成:
1, 2, 3, 1, 2, 3, 1, 2, 2