php - How to move array elements to top if compared with string? -
i have array $result getting mysql follows
array ( [0] => array ( [p_title] => apple new ipad (white, 64gb, wifi) ) [1] => array ( [p_title] => apple ipad mini/ipad mini retina belkin fastfit bluetooth wireless key ) [2] => array ( [p_title] => apple ipad air (16gb, wifi + cellular) ) )
and suppose getting sort value in $sort_by
variable. ex. currently,
$sort_by="apple ipad";
so want move each array elements have p_title "apple ipad" top.
so output array should be;
array ( [0] => array ( [p_title] => apple ipad air (16gb, wifi + cellular) ) [1] => array ( [p_title] => apple ipad mini/ipad mini retina belkin fastfit bluetooth wireless key ) [2] => array ( [p_title] => apple new ipad (white, 64gb, wifi) ) )
i ready edit code either in mysql query or in php.
use usort()
:
function sortx($a, $b) { if(strpos($a['p_title'],'apple ipad')!==false){ return -1; } return 1; } usort($array, 'sortx');
whenever preceding value contain string, pushed towards beginning of array.
if want use variable in usort()
function, need use objects:
class sorttitles{ public $string; function sortx($a, $b) { if(strpos($a['p_title'],$this->string)!==false){ return -1; } return 1; } public function sort_titles($array){ usort($array, 'self::sortx'); return $array; } } $sort = new sorttitles; $sort->string = 'apple ipad'; $array = $sort->sort_titles($array);