2

Please I need an effective way of sorting this kind of array with php...

    [
      'product' => ['order' => 2, 'parent' => null],
      'nam-product' => ['order' => 13, 'parent' => 'product'],
      'core' => ['order' => 5, 'parent' => null],
      'cart' => ['order' => 4, 'parent' => 'session'],
      'session' => ['order' => 4, 'parent' => null],
      'naivas-cart' => ['order' => 5, 'parent' => 'cart'],
      'user' => ['order' => 3, 'parent' => null],
    ];

Sort the array by order but also make sure parent doesn't come before child, I used uasort for the first condition like this

    uasort($plugin, function ($a, $b) use ($direction) {
        if ($a['order'] == $b['order']) {
            return 0;
        }

        if ($direction == 'dsc') {
            return $a['order'] < $b['order'] ? 1 : -1;
        }

        return $a['order'] > $b['order'] ? 1 : -1;
    });

Effective way of achieving the second condition eludes me.

  • You need to use `uksort()` so that the comparison function receives the keys. Otherwise, it can't tell whether one of them is the parent of another. – Barmar Aug 08 '18 at 20:14
  • Why are you using `->order` instead of `['order']`? That's for objects, not arrays. – Barmar Aug 08 '18 at 20:15
  • 1. create tree using references(so you will be able to do that with single pass). 2. remove all elements with `parent != NULL`. 3. flatten tree into list sorting items from `children` list by order – skyboyer Aug 08 '18 at 20:16
  • Thank u Barmar, I have updated it – Dayo Aderemi Aug 08 '18 at 20:17
  • Some related questions, I think you should be able to use or adapt their solutions: https://stackoverflow.com/questions/39121729/sort-array-values-based-on-parent-child-relationship?s=1|102.8231 https://stackoverflow.com/questions/36919534/sort-multidimensional-arrays-recursively-after-setting-up-child-parent-realtions?s=2|96.1078 – Barmar Aug 08 '18 at 20:35

0 Answers0