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
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']);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With