首页 > 解决方案 > best sorting method for merge two sorted array

问题描述

I have two group of array of object, say
group 1: (already sorted by title in SQL Query)
[{id: 21, title: "a"},{id: 62, title: "ab"},{id: 35, title: "abc"}]

group 2: (already sorted by title in SQL Query)
[{id: 23, title: "aba"},{id: 54, title: "abb"},{id: 46, title: "abe"}]

in fact, the real data is more complicated, so I can't merge and sort in MYSQL Query. I know I can merge and sort by array_merge and usort but I doubt if I use for-loop to sort is faster because these 2 groups were already sorted.

Would you provide a better method for how to use for loop to sort or any other better method? Thanks.

My original query is

group 1
SELECT a.*, c.state, c.version, c.len, c.price, GROUP_CONCAT(d.tag) AS tag, e.keywords, e.description, e.cat, e.cover, f.url AS cover_url, f.server AS cover_server, h.url AS thumbnail_url, h.zip AS thumbnail_zip FROM ro_final_entries a LEFT JOIN ro_book_tag b ON b.bid = a.id AND a.id NOT IN (SELECT bookID FROM ro_app_bookshelf WHERE specify=1) INNER JOIN ro_version c ON c.id = a.id AND (c.state = ?) LEFT JOIN ro_final_tag d ON b.tid = d.id LEFT JOIN ro_final_book_info e ON e.id = a.id LEFT JOIN ro_assets f ON substr(SUBSTRING_INDEX(e.cover, '/', 4),10) = f.id LEFT JOIN `ro_final_entries` g ON g.pid = a.id RIGHT JOIN `ro_final_thumbnail` h ON h.bid = g.id AND h.bid AND (h.pid = 'cover' OR (h.page_index = 0 AND h.pid <> 'cover')) WHERE (a.type = 'book')

group 2:
SELECT a.*, c.state, c.version, c.len, c.price, GROUP_CONCAT(d.tag) AS tag, e.keywords, e.description, e.cat, e.cover, f.url AS cover_url, f.server AS cover_server, GROUP_CONCAT(i.url) AS thumbnail_url, GROUP_CONCAT(i.zip) AS thumbnail_zip FROM ro_final_entries a LEFT JOIN ro_book_tag b ON b.bid = a.id AND a.id NOT IN (SELECT bookID FROM ro_app_bookshelf WHERE specify=1) INNER JOIN ro_version c ON c.id = a.id LEFT JOIN ro_final_tag d ON b.tid = d.id LEFT JOIN ro_final_book_info e ON e.id = a.id LEFT JOIN ro_assets f ON substr(SUBSTRING_INDEX(e.cover, '/', 4),10) = f.id LEFT JOIN `ro_final_entries` g ON g.pid = a.id LEFT JOIN `ro_final_entries` h ON h.pid = g.id RIGHT JOIN `ro_final_thumbnail` i ON i.bid = h.id AND i.bid AND (i.pid = 'cover' OR (i.page_index = 0 AND i.pid <> 'cover')) WHERE (a.type = 'collection')

标签: phpmysqlsorting

解决方案


You can try below method to sort array

function sortBy($field, &$array, $direction = 'asc'){
        usort($array, create_function('$a, $b', '
                $a = $a["' . $field . '"];
                $b = $b["' . $field . '"];

                if ($a == $b) return 0;

                $direction = strtolower(trim($direction));

                return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
            '));

        return true;
    }

推荐阅读