phpmysqlsortingcodeigniterunion

Sort rows of a 2d array by one column or another (if the first column doesn't exist)


In my application I'm performing a keyword search on two different tables and on two different column names. I want to combine the movies.title and the people.title so that I can sort all of them together alphabetically. Currently I merge my two queries and the results come back first with the movies and then with the people.

public function get_from_keyword($keyword)
{ 
    $movie_query = $this->db
    ->select('id, title, release_year')
    ->from('movies')
    ->like('movies.title', $keyword)
    ->where('movies.id IS NOT NULL', null)
    ->get()
    ->result();

    $person_query = $this->db
    ->select('name, person_id')
    ->from('people')
    ->like('name', $keyword)
    ->get()
    ->result();

    $merged_queries = array_merge($movie_query, $person_query);
    return $merged_queries;
}

I'm not sure if I need to dynamically alter one of the column names in the SELECT query in order to merge them together.


Solution

  • Try use an "AS" to name both the movies.title and the people.name fields the same like:

       $person_query = $this->db
        ->select('name', 'MySortTitle') // AS
        ->select('person_id')
        ->from('people')
        ->like('name', $keyword)
        ->get()
        ->result();
    

    And the same for the movie query:

        $movie_query = $this->db
        ->select('title', 'MySortTitle') // AS
        ->select('id, release_year')
        ->from('movies')
        ->like('movies.title', $keyword)
        ->where('movies.id IS NOT NULL', null)
        ->get()
        ->result();
    

    Then sort the merged array by MySortTitle.