Trying to modify an array to avoid overlapping key-value pairs using PHP
I have an array that looks like this:
Array([5258]=>5274,
[5261]=>5281,
[5264]=>5287,
[5271]=>5289 );
I want to modify this array so that any overlaps in key value pairs are removed.
To elaborate, the first key value pair should become [5258]=>5289
, because the numerical value of the each of the rest of the keys is less than 5274, the original value corresponding to the first key.
What would be the best way to do this using PHP? I'll appreciate some pointers on this.
Thanks.
EDIT: Just a reword to the background for my question: If there's an array like this:
Array([10]=>12
[11]=>15
[16]=>20)
I want to derive another array/modify the same array to get
A开发者_开发技巧rray([10]=>15
[16]=>20)
I hope this makes things clearer.
Is this a game of guess the actual question?
This is my answer to what I think the question is:
$arr = Array(
5258=>5274,
5261=>5281,
5264=>5287,
1=>100,
50=>70,
40=>130,
5271=>5289
);
ksort($arr);
$out = array();
$start = null;
foreach ( $arr as $from=>$to )
{
if ( $start === null )
{
$start = $from;
$end = $to;
} else {
if ( $from < $end )
{
$end = max($end,$to);
} else {
$out[$start] = $end;
$start = null;
}
}
}
if ( $start !== null ) $out[$start] = $end;
print_r($out);
output:
Array
(
[1] => 130
[5261] => 5289
)
<?php
$arr = array(5258=>5274,
5261=>5281,
5264=>5287,
5271=>5289 ,
5301=>5400);
ksort($arr);
$new = array();
$currentkey = reset(array_keys($arr));
$currentvalue = reset($arr);
foreach($arr as $key=>$value){
if($key > $currentvalue){
$new[$currentkey] = $currentvalue;
$currentkey = $key;
}
$currentvalue = max($currentvalue,$value);
}
$new[$currentkey] = $currentvalue;
var_dump($new);
?>
Take a look at usort()
but I'm not quite sure how it works. It's a bit black magic for me. At a guess, make a function which compares the key values and orders the array like that.
Or you could tinker with array_merge()
Apologies for a waffling answer, I don't quite understand your question, or the criteria for how you want to merge/sort your array
精彩评论