php - Echoing Sorted Multidimensional Array -
ok, creating web app php , mysqli. have table friends simple set up:
f_id int(11) uid int(11) fids text now row each user fids consisting of lot of numerical values (other userids) separated commas like: 1,2,3 utilize function each user's friends:
function getfriends($db, $userid) { $q = $db->query("select fids friends uid='$userid'"); $ar = $q->fetch_assoc(); $friends = $ar['fids']; $fr = explode(",", $friends); homecoming $fr; } but each posts comments appear each of friends. problem comes trying sort these comments time posted. lets comments table is:
c_id int(11) uid int(11) c_text text c_time int(11) i want able comments posted each 'friend' set them array together, sort them c_time value, values particular row in comments table.
the problem comes how i've set friends table. i'm using:
$fr = getfriends($db, $userid); $updates = array(); $i = 0; foreach( $fr $friend) { // updates friends , self $q = $db->query("select up.*, u.* updates left bring together users u on u.id = '$friend' (up.userid = '$userid') order up.up_id desc"); while($ar = $q->fetch_array(mysqli_both)) { $updates[$i] = $ar; $i++; } } $sortarray = array(); foreach($updates $update){ foreach($update $key=>$value){ if(!isset($sortarray[$key])){ $sortarray[$key] = array(); } $sortarray[$key][] = $value; } } $orderby = "up_id"; array_multisort($sortarray[$orderby],sort_desc,$updates); $updates_limit = array_slice($updates, 0, 20); to comments each friend, sorting time, slicing first 20. when var_dump($updates_limit) takes lastly row in comments table, , makes each friend posted same comment.
can see problem or improve way of addressing issue?
i'd refactor friends table more this: (also, utilize english language - characters inexpensive :c))
create table friends ( user_id int foreign key references user(id) , friend_id int foreign key references user(id) , primary key (user_id, friend_id) ); then can take same comment table:
create table comment ( comment_id int primary key , user_id int foreign key references user(id) , comment_text text , comment_time datetime ); and "query friend's comments" becomes:
select comment_id, comment.user_id, comment_text, comment_time friends inner bring together comment on comment.user_id = friends.friend_id friends.user_id = ? #target order comment_time desc limit 0, 20; you can speed adding few indexes - comment(user_id).
php mysql arrays sorting
No comments:
Post a Comment