Reputation: 1378
I have the following array that indicates the order on how to sort the DATA array:
$PARENT_ID_ORDER = array(1, 3, 2);
Here's the DATA array, which contains PARENT_ID key, I want to sort by PARENT_ID key using my PARENT_ID_ORDER:
$DATA = array (
array (
'PARENT_ID' => 2;
),
array (
'PARENT_ID' => 2;
),
array (
'PARENT_ID' => 1;
),
array (
'PARENT_ID' => 3;
),
array (
'PARENT_ID' => 1;
),
array (
'PARENT_ID' => 2;
),
array (
'PARENT_ID' => 2;
)
);
The expected output:
array(
[0] => Element Object
(
[PARENT_ID] => 1,
),
[1] => Element Object
(
[PARENT_ID] => 1,
),
[2] => Element Object
(
[PARENT_ID] => 3,
),
[3] => Element Object
(
[PARENT_ID] => 2,
),
[4] => Element Object
(
[PARENT_ID] => 2,
),
[5] => Element Object
(
[PARENT_ID] => 2,
),
[6] => Element Object
(
[PARENT_ID] => 2,
)
);
How can I provide my order array to sort function so it gets sorted this way? Thanks!
Upvotes: 0
Views: 383
Reputation: 157
I think you're looking for this http://php.net/manual/en/function.usort.php. You can use this along with binary search or inbuilt array_search if array is small
Upvotes: 1