0

I have to sort below given array by Priority. If priority value is 0 then not include in sorting array. I have tried many ways but not getting output as expected.

Array
(
[recently_viewed] => Array
    (
        [priority] => 1
        [no_of_products] => 1
    )

[recently_visited_cat] => Array
    (
        [priority] => 1
        [no_of_products] => 1
    )

[last_ordered_items] => Array
    (
        [priority] => 3
        [no_of_products] => 3
    )

[searched_based] => Array
    (
        [priority] => 0
        [no_of_products] => 4
    )

[cart_based] => Array
    (
        [priority] => 1
        [no_of_products] => 5
    )

[wishlist_based] => Array
    (
        [priority] => 1
        [no_of_products] => 6
    )

[sku_based] => Array
    (
        [priority] => 0
        [no_of_products] => 7
    )
)

Please help me with this.

Magecode
  • 225
  • 2
  • 6
  • 16

3 Answers3

1

You can use array_filter() function to exclude records with 0 priority. After it you can sort the array with help uasort() function. For example:

$arr = array_filter($arr, function($element) {
    return $element['priority'] > 0;
});

uasort($arr, function ($a, $b) {
    if ($a['priority'] === $b['priority']) {
        return 0;
    }
    return ($a['priority'] < $b['priority']) ? -1 : 1;
});
Maksym Fedorov
  • 6,383
  • 2
  • 11
  • 31
  • Your `uasort` callback code can simply be `return $a['priority'] <=> $b['priority']` or `return $a['priority'] - $b['priority']` (pre PHP7). Note that it also depends if a higher priority has a higher or lower priority value (otherwise just switch operands). – Jeto Apr 10 '19 at 06:55
  • @Jeto of course, but I don't know what PHP version use author, therefore I don't use <=> operator – Maksym Fedorov Apr 10 '19 at 07:03
  • Right--the other alternative (with `-`) works on any version though. – Jeto Apr 10 '19 at 07:13
1

You can us array_filter (doc - for check bigger then 0) and then uasort (doc):

$arr = [];
$arr["recently_viewed"] = ["priority" => 1, "no_of_products" =>1];
$arr["searched_based"] = ["priority" => 0, "no_of_products" =>4];
$arr["last_ordered_items"] = ["priority" => 3, "no_of_products" =>3];

$arr = array_filter($arr, function ($e) {return $e["priority"];});
uasort($arr, function($a, $b) {
    return $a['priority'] - $b['priority'];
});

Live example: 3v4l

dWinder
  • 11,597
  • 3
  • 24
  • 39
0

You can use array_filter with callback function to remove the values with ZERO

$arr = array_filter($arr, function ($e) {return $e["priority"];});

This will remove all the sub-array which has priority values ZERO.

Now you can apply usort to sort the array

usort($arr, function($a, $b)  {
    return $a['priority'] <=> $b['priority'];
});

See Working Code Live

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
  • First notice the keys of the array - OP probably want to keep them - so use `uasort` and not `usort`. Second - what is different here then other answer? – dWinder Apr 10 '19 at 08:22