What is the best approach to sorting data in PHP based on specific words in a MySQL query result?

When sorting data in PHP based on specific words in a MySQL query result, you can use the usort() function along with a custom comparison function. This function will check for the specific words you want to prioritize and sort the data accordingly. By defining your own sorting logic, you can achieve the desired order of results based on the presence of specific words.

// Sample MySQL query result
$queryResult = [
    ['id' => 1, 'name' => 'Apple'],
    ['id' => 2, 'name' => 'Banana'],
    ['id' => 3, 'name' => 'Orange'],
    ['id' => 4, 'name' => 'Apple Banana'],
    ['id' => 5, 'name' => 'Banana Orange'],
];

// Function to sort data based on specific words
usort($queryResult, function($a, $b) {
    $specificWords = ['Banana', 'Orange']; // Words to prioritize
    foreach ($specificWords as $word) {
        $hasWordA = strpos($a['name'], $word) !== false;
        $hasWordB = strpos($b['name'], $word) !== false;
        
        if ($hasWordA && !$hasWordB) {
            return -1;
        } elseif (!$hasWordA && $hasWordB) {
            return 1;
        }
    }
    
    return 0;
});

// Output sorted data
foreach ($queryResult as $row) {
    echo $row['name'] . "\n";
}