0

Is it possible to sort rows by a custom array of ids given from another table or somehow.

$str = "5,2,3,6,911,18,118,65,985,15...";  

$arr = explode(',', $str);

function get_titles($status){
    global $db;
    $sql = "select * from arts where status = :astatus order by " . $arr . " asc";
    $st = $db->prepare($sql);
    $st->execute([":astatus" => $status]);
    ...
}
  • This might help... https://stackoverflow.com/questions/348410/sort-an-array-by-keys-based-on-another-array – Nick Dec 29 '18 at 05:07
  • 1
    Possible duplicate of [MySQL sort order by array value](https://stackoverflow.com/questions/8055138/mysql-sort-order-by-array-value) – Sean Dec 29 '18 at 05:19
  • @Sean, both answers on your link are about `sort by field`. I have no a field as sort criteria, but an external array. –  Dec 29 '18 at 05:24
  • the field is what to order by. Your array is the additional values. ie. `... ORDER BY field(id, ". $str .") ...` – Sean Dec 29 '18 at 05:30
  • If the answer is correct please approve it – Blaztix Jan 31 '19 at 18:34

1 Answers1

0

If you want order by custom id order...

# $str = "5,2,3,6,911,18,118,65,985,15...";
# Values separated by comma
# It can be from array
#     $str = implode(",",[5,2,3,6,911,18,118,65,985,15])

$str = "5,2,3,6,911,18,118,65,985,15";  

function get_titles($status,$arr){
    global $db;
    $sql = "SELECT * FROM arts WHERE status = :astatus ORDER BY FIELD(id,".$arr .") ASC";
    $st = $db->prepare($sql);
    $st->execute([":astatus" => $status]);
    ...
}

get_titles($status,$str)
Blaztix
  • 1,223
  • 1
  • 19
  • 28