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]);
    ...
}
5
  • This might help... stackoverflow.com/questions/348410/… Commented Dec 29, 2018 at 5:07
  • 1
    Possible duplicate of MySQL sort order by array value Commented Dec 29, 2018 at 5:19
  • @Sean, both answers on your link are about sort by field. I have no a field as sort criteria, but an external array. Commented Dec 29, 2018 at 5:24
  • the field is what to order by. Your array is the additional values. ie. ... ORDER BY field(id, ". $str .") ... Commented Dec 29, 2018 at 5:30
  • If the answer is correct please approve it Commented Jan 31, 2019 at 18:34

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.