d123546
d123546

Reputation: 247

Laravel How to sort Collection based on array indexes

Basically title is the questions itself. I have a collection, which stores arrays in one of the field. I made a sorting algorithm to sort out those arrays and the result is sorted array:

array:8 [▼
  3 => array:5 [▼
    5 => 100
    1 => 50
    2 => 30
    3 => 20
    4 => 10
  ]
  6 => array:5 [▼
    1 => 100
    5 => 50
    3 => 30
    4 => 20
    2 => 10
  ]
  2 => array:5 [▼
    3 => 100
    5 => 50
    4 => 30
    1 => 20
    2 => 10
  ]

The index of this array 3,6,2 is the ID of the collection. How can I order collection based on this ID's in same order as array ?

Upvotes: 0

Views: 2028

Answers (1)

Nitish Kumar
Nitish Kumar

Reputation: 6276

Suppose you have array inside $a variable:

$a = array:8 [▼
      3 => array:5 [▼
        5 => 100
        1 => 50
        2 => 30
        3 => 20
        4 => 10
      ]
      6 => array:5 [▼
        1 => 100
        5 => 50
        3 => 30
        4 => 20
        2 => 10
      ]
      2 => array:5 [▼
        3 => 100
        5 => 50
        4 => 30
        1 => 20
        2 => 10
      ]
    ];

then you can sort in ascending order with reference of key from ksort() and have something like this:

foreach($a as $b)
{
    ksort($b);
}

and similarly for descending order you can use krsort().

Hope this helps.

Upvotes: 2

Related Questions