出个排序题目:
$data=[1,1,1,1,2,2,2,2,5,5,5,8,8,8,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4]
怎么把值为1,2,3,4的数据分成4个数组
如:$data1[1]=[1,1,1,1]
$data1[2]=[2,2,2,2,2,2,2]
$data1[3]=[5,5,5]
$data1[4]=[8,8,8]
数据上限不定的时候怎么写?就是说不一定是4个数组 有N个,N是未知数
并且最后结果的数组必须是从1开始的一次递增的索引的数组
我的解
Code
<?php
$data=array(1,1,1,1,2,2,2,6,6,2,2,2,2,3,3,3,5,5,5,3,3,3,3,4,4,4,4,4,4,4);
$data1=array();
$data2=array();
$pos=0;
for($i=0;$i<sizeof($data);$i++)
{
if(my_in_array($data[$i],$data2,&$pos))
{
$data1[$pos][]=$data[$i];
}
else{
$data2[]=$data[$i];
$pos=count($data2)-1;
$data1[$pos][]=$data[$i];
}
}
function my_in_array($str,$arr,&$pos)
{
for($j=0;$j<sizeof($arr);$j++)
{
if($str==$arr[$j])
{
$pos=$j;
return true;
}
}
return false;
}
print_r($data1);
print_r($data2);
?>
结果如下:
Array
(
[0] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
)
[1] => Array
(
[0] => 2
[1] => 2
[2] => 2
[3] => 2
[4] => 2
[5] => 2
[6] => 2
)
[2] => Array
(
[0] => 6
[1] => 6
)
[3] => Array
(
[0] => 3
[1] => 3
[2] => 3
[3] => 3
[4] => 3
[5] => 3
[6] => 3
)
[4] => Array
(
[0] => 5
[1] => 5
[2] => 5
)
[5] => Array
(
[0] => 4
[1] => 4
[2] => 4
[3] => 4
[4] => 4
[5] => 4
[6] => 4
)
)
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 3
[4] => 5
[5] => 4
)