我有一个数组$result从
mysql获取如下
- Array
- (
- [0] => Array
- (
- [p_title] => Apple The 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)
- )
- )
并假设我在$sort_by变量中按值排序.
对于前目前,
$sort_by="Apple ipad";
所以我想将每个拥有p_title“Apple ipad”的数组元素移到顶部.
所以我的输出数组应该是;
- 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 The New iPad (White,WiFi)
- )
- )
使用usort():
- function sortx($a,$b) {
- if(strpos($a['p_title'],'Apple ipad')!==false){
- return -1;
- }
- return 1;
- }
- usort($array,'sortx');
只要前面的值包含该字符串,它就会被推向数组的开头.
如果要在usort()函数中使用变量,则需要使用对象:
- 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);