How to group array values to different levels in PHP?
$arr = array(25,41,120,...36);
How to group values in $arr
to specified integer range $start ~ $end
?
For example , if the level range is 1~5(1,2,3,4,5)
, how can I specify a level for each element of $arr
?
开发者_StackOverflowThe only principle is that larger value should map to larger level, and should cover the entire level range as possible.
UPDATE
I'll give a maybe over simplified example:
if the levels are 1~4
, and the $arr
is array(25,41,120,36)
,then obviously the best way to assign level numbers should be:
25 -> 1
41 -> 3
120 -> 4
36 -> 2
Frist, sort it: http://php.net/manual/en/function.sort.php (and if your array has associative keys, check out asort()
)
Then, I would make a new array that would hold your result. Iterate though $arr
and if do a check that the value is between your bounds. If it is, add it to the new array.
$NewArray = array();
$arr = sort($arr);
$i = 0;
while ($i < count($arr))
{
if ($arr[$i] <= $HighValue && $arr[$i] >= $LowValue)
{
$NewArray[] = $arr[$i];
}
$i++;
}
Maybe you can try this:
$inputarr = array(1,3,5,7,2,4,6,8);
$levelcount = 3; //assume you have 3 levels
$csize = ceil(count($inputarr)/$levelcount);
sort($inputarr);
print_r(array_chunk($inputarr,$csize,true))
The output is
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[3] => 4
[4] => 5
[5] => 6
)
[2] => Array
(
[6] => 7
[7] => 8
)
)
I do not quite understand how you want to associate the numbers to their level. Presumably you want the number as the key and the level as the value in an associative array. At least that is what your example looked like.
Also, I do not understand the function of $start and $end. If $start is 5 and $end is 50, but there are only 10 numbers, what happens? What if $start is 2 and $end is 7 and there are 10 numbers? I replaced the mechanism with just $levelOffset. It is my guess as to what you really wanted.
<?php
$levelOffset = 1;
$arr = array(25,41,120,36);
sort($arr);
$arr = array_flip($arr);
foreach ($arr as &$level) {
$level += $levelOffset;
}
/*
var_dump($arr) gives:
array(4) {
[25]=>
int(1)
[36]=>
int(2)
[41]=>
int(3)
[120]=>
&int(4)
}
*/
精彩评论