Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

php - 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

question from:https://stackoverflow.com/questions/66050768/bringing-the-top-5-values-any-advice

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...