如果与字符串相比,如何将数组元素移动到顶部?

Muj*_*KAS 8 php mysql

我有一个数组$ 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)
        )
)
Run Code Online (Sandbox Code Playgroud)

并假设我在$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, 64GB, WiFi)
        )
)
Run Code Online (Sandbox Code Playgroud)

我准备在mysql查询或php中编辑代码.

n-d*_*dru 7

用途usort():

 function sortx($a, $b) {
    if(strpos($a['p_title'],'Apple ipad')!==false){
        return -1;
    }
    return 1;
}

usort($array, 'sortx');
Run Code Online (Sandbox Code Playgroud)

只要前面的值包含该字符串,它就会被推向数组的开头.

如果要在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);
Run Code Online (Sandbox Code Playgroud)