Sobes.tech
Junior — Middle

How can you obtain a list of top records limited by a specific field value?

sobes.tech AI

Answer from AI

To get a list of top records limited by a specific field value in PHP, you typically use array sorting and the array_filter function or an SQL query if the data is stored in a database.

Example with an array:

$data = [
    ['id' => 1, 'score' => 50],
    ['id' => 2, 'score' => 80],
    ['id' => 3, 'score' => 70],
    ['id' => 4, 'score' => 90],
];

// Limit by 'score' >= 70
$filtered = array_filter($data, function($item) {
    return $item['score'] >= 70;
});

// Sort by 'score' descending
usort($filtered, function($a, $b) {
    return $b['score'] <=> $a['score'];
});

// Get top records, for example, top 3
$top = array_slice($filtered, 0, 3);

print_r($top);

If the data is in a database, it's easier to do an SQL query with WHERE and ORDER BY:

SELECT * FROM table_name WHERE score >= 70 ORDER BY score DESC LIMIT 3;

This way, you will get the top records satisfying the condition on the field value.