Reputation: 7404
I have following array's :
Array
(
[0] => 147
[1] => hello
[2] => Asia/Kolkata
[3] => Upcoming
)
Array
(
[0] => 148
[1] => hello world
[2] => Asia/Karachi
[3] => Live
)
Array
(
[0] => 147
[1] => ABCD
[2] => Asia/Colombo
[3] => NA
)
The above array's are coming from database expect the last 6th value is coming from API dynamically. I have pushed that value to database array by using array push.
See the code below:
function compareArrayItems($a, $b) {
$order = array(
"Live",
"Upcoming",
"NA"
);
$aWeight = array_search($a[9], $order);
$bWeight = array_search($b[9], $order);
if ($aWeight === false || $bWeight === false || $aWeight === $bWeight)
return 0;
return $aWeight < $bWeight ? 1 : - 1;
}
$sArr = array();
while ($kj = mysqli_fetch_array($result)) {
$arrk = get_status_for_hashtag($kj['start_time'], $kj['end_time'], $kj['day'], $kj['timezone']);
array_push($kj, $arrk);
$sArr[] = $kj;
}
usort($sArr, "compareArrayItems");
Here the status is nothing but the last value that is : upcoming, live, NA. Currently sorting is coming as usual means according to the database but I want to sort this according to the status means last value. I want live should come first, then upcoming 2nd and NA 3rd. Its not possible by using order-by query because status is not coming from database. Its coming from API and I just merge it with database array.
Hope you got my point.
Thanks.
Upvotes: 1
Views: 82
Reputation: 4110
You can use usort providing a custom $cmp_function
comparing $a[3]
and $b[3]
values.
UPDATE
Here is an example of usage:
$arr = array(
array(147, "hello", "Asia/Kolkata", "Upcoming"),
array(148, "hello world", "Asia/Karachi", "Live"),
array(147, "ABCD", "Asia/Colombo", "NA"),
);
print_r($arr);
usort($arr, "compareArrayItems");
print_r($arr);
and custom function for sorting array items in order "Live", "Upcoming", "NA":
function compareArrayItems($a, $b)
{
$order = array(
"Live",
"Upcoming",
"NA"
);
$aWeight = array_search($a[3], $order);
$bWeight = array_search($b[3], $order);
if ($aWeight === false || $bWeight === false || $aWeight === $bWeight)
return 0;
return $aWeight > $bWeight ? 1 : - 1;
}
For more information on callbacks you can refer to this page.
Upvotes: 2
Reputation: 4996
$rows = $result->fetch_all(MYSQLI_ASSOC);
$sort = [];
foreach ($rows as &$row)
{
$row[] = $sort[] = get_status_for_hashtag($row['timezone']);
}
unset($row);
array_multisort($sort, $rows);
Upvotes: 1