Skora
Skora

Reputation: 127

bringing the top 5 values, any advice?

I am not an expert on php

So I have a question, is there a shortcut for this code?

The code worked briefly, bringing the top 5 values

//vid_id.json {"video_id":{"nljJo":6,"Eg50":5,"ydIsc":1,"J9-a0":1,"2h8fU":1, ..

$data = json_decode(file_get_contents('vid_id.json'), true);
asort($data['video_id']);
$items = array();
foreach ($data['video_id'] as $x => $x_value) {
    $items[] = $x;
}
$c = array_values(array_reverse($items));
$Top5 = null;
$num = 1;
foreach ($c as $key => $value) {
    if (4 >= $key) {
        $Top5 .= $num . " - " . $value . "<br>";
        $key++;
        $num++;
    }
}
echo $Top5;

It works very well, but I was wondering if there was a better optimize

Upvotes: 0

Views: 53

Answers (2)

nice_dev
nice_dev

Reputation: 17805

IMO, you can make use of data structure called max heap to get the top 5 data. This would also avoid the cost of sorting the entire dataset(of say a million rows).

PHP implements SplHeap heap class already. Just impose your own compare() method to make it behave like a max heap.

Process is simple. Insert all elements in queue. Extract the top 5 from it.

<?php

class MaxHeap extends SplHeap{
    protected function compare($val1, $val2){
        return $val1 <=> $val2;
    }
}

$heap = new MaxHeap();
foreach([8,5,2,0,1,7,9,0,5,3,6,0,48441,56] as $val){
    $heap->insert($val);
}

Now, collect the top 5.

<?php

$top_five = [];

for($i = 1; $i <= 5; ++$i){
    $top_five[] = $heap->extract();
}

print_r($top_five);

Upvotes: 1

Jaquarh
Jaquarh

Reputation: 6693

Your foreach just pulls the array_keys() so can be dropped. You can also use array_splice() to get the first 5 records as noted in the comments by Pelippe Duarte.

$response = json_decode(file_get_contents('vid_id.json'), true);

asort($response);

$top5 = array_splice(                                       // Split
            array_values(                                   // Loose Original Keys
                array_reverse(                              // I Assume For Sorting
                    array_keys($response['video_id'])       // Dropped Foreach
                )
            )
        , 0, 4);                                           // Offset 0, Length

This is untested as I do not know what your vid_id.json holds but theoretically, this should work.


$top5 will now be an array you can loop through on your front-end and output rather than your back-end.

Upvotes: 1

Related Questions