Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_slice for associative array

I have an array with indexes as timestamps. I tried array_slice to get all values between a time range but it doesn't seem to work.

$data = array_slice(["1549440811" => 1, "1549448226" => 2, "1551108588" => 3 ], 0, 1549460338);

I should get the $data as ["1549440811" => 1, "1549448226" => 2] but it doesn't work that way.

To get the right data I have to use

$data = array_slice(["1549440811" => 1, "1549448226" => 2, "1551108588" => 3 ], 0, 2);

But the problem is the records can have random timestamps and no. of records. So I am unable to figure out the offset which is 2 in this case.

I know the code below with a few changes might work for small range but not for my timestamps as $myrange would have a lot of data.

$myrange = range(0,1549460338);
$output = array_intersect(["1549440811" => 1, "1549448226" => 2, "1551108588" => 3 ] , $myrange );

I am avoiding looping through the array as the array has a lot of data. Also I have a lot of timestamps to check. This code is a simplified logic of a bigger code with records from database indexed with timestamps.

Is there any other way I could get the desired data?

like image 729
Mehravish Temkar Avatar asked Oct 19 '25 22:10

Mehravish Temkar


1 Answers

Simple for-loop should do:

$arr = ["1549440811" => 1, "1549448226" => 2, "1551108588" => 3 ];
$range = "1549460338";
foreach($arr as $k => $v) {
    if ($range > $k)
        break;
    $newArr[$k] = $v;
}

You can also use array_filter (doc):

$filtered = array_filter( $arr,
    function ($key) use ($range) {return $range > $key;},
    ARRAY_FILTER_USE_KEY
);

Example: 3v4l

Edit:

Fastest way (consider your array is sorted) is to extract the keys with $keys = array_keys($arr); and then search for the $range using binary search (O(log(n))) -> then use array_slice with that index.

like image 88
dWinder Avatar answered Oct 22 '25 14:10

dWinder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!