Custom Sort Arrays

$original_ids = array(1, 2, 3, 4); //<--- Original values without sorted. $sorted_ids = array(4, 1, 3); //<--- Fixed values (sort by this) $result_ids = array(); //<--- The result array after sorted 

I just want to reinstall the associated array and sort it by $sorted_ids (if you understand)

$ result_ids should be ... array(4, 1, 3, 2) ( 2 is not in the $ original_ids array, so put it in last )

I got attached to a code like ...:

 foreach ($sorted_ids as &$id) { if (in_array($id , $original_ids)) { $result_ids[] = $id; } else { } } 

But I have no idea how to push arrays without matching for the last $ result_ids array.

Comment if you do not understand.

+4
source share
5 answers
 $result_ids = array_merge( array_intersect($sorted_ids, $original_ids), // the values that match sorter array_diff($original_ids, $sorted_ids) // append the rest ); 
+1
source
 foreach ($sorted_ids as $id) { if (in_array($id , $original_ids)) { $result_ids[] = $id; } else { $addToEnd[] = $id } } array_merge($result_ids, $addToEnd); 

Your use of &$id pointless because you are pushing its value. You do not need a link.

+1
source
 array_merge($sorted_ids, array_diff($original_ids, $sorted_ids)) 
+1
source
 $original_ids = array(1, 2, 3, 4); $sorted_ids = array(4, 1, 3); foreach($original_ids as $key=>$val){ if(in_array($val,$sorted_ids)){ unset($original_ids[$key]); } } $result_ids = array_merge($sorted_ids,$original_ids); print_r($result_ids); 
0
source

you can use this code:

 <?php foreach ($sorted_ids as &$id) { if (sort($id)) { $result_ids[] = $id; } else { } } ?> 

he will do exactly what you need

0
source

All Articles