Skip to main content

Posts

Showing posts from September, 2022

Sort an Array by keys based on another Array

 <?php $customer [ 'address' ] = '123 fake st' ; $customer [ 'name' ] = 'Tim' ; $customer [ 'dob' ] = '12/08/1986' ; $customer [ 'dontSortMe' ] = 'this value doesnt need to be sorted' ; $properOrderedArray = array_merge ( array_flip ( array ( 'name' , 'dob' , 'address' )), $customer ); // or $properOrderedArray = array_replace ( array_flip ( array ( 'name' , 'dob' , 'address' )), $customer );

Custom Sorting Array List in PHP

 <?php $order = array("Z","Srilanka","34", "Canada", "India", "USA"); $array = array(     array('id' => 7867867, 'title' => 'USA'),     array('id' => 3452342, 'title' => 'India'),     array('id' => 1231233, 'title' => 'Srilanka'),     array('id' => 5867867, 'title' => 'Z'), ); usort($array, function ($a, $b) use ($order) {     $pos_a = array_search($a['title'], $order);     $pos_b = array_search($b['title'], $order);     return $pos_a - $pos_b; }); print_r($array); ?>