Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usort by specific string value

I have an array of products. Each product is associative array and has an id, language type and product type id.

[1] => ["1", "en", "1"],
[2] => ["3", "fr", "1"],
[3] => ["7", "es", "1"],
[4] => ["2", "en", "2"],
[5] => ["4", "fr", "2"],
[6] => ["6", "es", "2"],
[7] => ["8", "en", "3"],
[8] => ["5", "ru", "3"],

I already sorted the array with product ids with usort

usort($data, function ($a, b) {

    return ($a['product_type_id'] - $b['product_type_id']);
});

I want to sort everything by product type id and after that I also want all items with language id 'en' appear in the beginning.

[1] => ["1", "en", "1"],
[2] => ["2", "en", "2"],
[3] => ["8", "en", "3"],
[4] => ["3", "fr", "1"],
[5] => ["7", "es", "1"],
[6] => ["4", "fr", "2"],
[7] => ["6", "es", "2"],
[8] => ["5", "ru", "3"],

I played around with usort in many different ways to achieve these but was not able to. I even wrote a separate usort which takes the sorted array and only makes "en" to the top. After that sort "en" is on the top but order of product types are completely destroyed. This is my second usort

usort($dataSortedByProductTypeId, function ($a, $b) {
    if($a['language_id'] == 'en'){
        if($b['language_id'] == 'en'){
            return 0;
        } else {
            return -1;
        }
    } else {
        return 1;
    }
});

Please help

like image 619
user3410843 Avatar asked Sep 16 '25 16:09

user3410843


1 Answers

How about something like:

$array = [
    ['id' => '1', 'lang' => 'en', 'pid' => '1'],
    ['id' => '3', 'lang' => 'fr', 'pid' => '1'],
    ['id' => '7', 'lang' => 'es', 'pid' => '1'],
    ['id' => '2', 'lang' => 'en', 'pid' => '2'],
    ['id' => '4', 'lang' => 'fr', 'pid' => '2'],
    ['id' => '6', 'lang' => 'es', 'pid' => '2'],
    ['id' => '8', 'lang' => 'en', 'pid' => '3'],
    ['id' => '6', 'lang' => 'ru', 'pid' => '3']
];

usort($array, function ($a, $b) {
    if ($a['lang'] == $b['lang']) {
        return ($a['pid'] - $b['pid']);
    }

    if ($a['lang'] == 'en') {
        return -1;
    } elseif ($b['lang'] == 'en') {
        return 1;
    } else {
        return ($a['pid'] - $b['pid']);
    }
});
like image 67
user372495 Avatar answered Sep 19 '25 06:09

user372495