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

前端之家收集整理的这篇文章主要介绍了php – 如果与字符串相比,如何将数组元素移动到顶部?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个数组$result从 mysql获取如下
  1. Array
  2. (
  3. [0] => Array
  4. (
  5. [p_title] => Apple The New iPad (White,64GB,WiFi)
  6. )
  7. [1] => Array
  8. (
  9. [p_title] => Apple ipad Mini/ipad Mini Retina Belkin Fastfit Bluetooth Wireless Key
  10. )
  11. [2] => Array
  12. (
  13. [p_title] => Apple ipad Air (16GB,WiFi + Cellular)
  14. )
  15. )

并假设我在$sort_by变量中按值排序.
对于前目前,

$sort_by="Apple ipad";

所以我想将每个拥有p_title“Apple ipad”的数组元素移到顶部.

所以我的输出数组应该是;

  1. Array
  2. (
  3. [0] => Array
  4. (
  5. [p_title] => Apple ipad Air (16GB,WiFi + Cellular)
  6. )
  7. [1] => Array
  8. (
  9. [p_title] => Apple ipad Mini/ipad Mini Retina Belkin Fastfit Bluetooth Wireless Key
  10. )
  11. [2] => Array
  12. (
  13. [p_title] => Apple The New iPad (White,WiFi)
  14. )
  15. )

我准备在mySQL查询PHP中编辑代码.

使用usort():
  1. function sortx($a,$b) {
  2. if(strpos($a['p_title'],'Apple ipad')!==false){
  3. return -1;
  4. }
  5. return 1;
  6. }
  7.  
  8. usort($array,'sortx');

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

如果要在usort()函数中使用变量,则需要使用对象:

  1. class SortTitles{
  2. public $string;
  3. function sortx($a,$b) {
  4. if(strpos($a['p_title'],$this->string)!==false){
  5. return -1;
  6. }
  7. return 1;
  8. }
  9. public function sort_titles($array){
  10. usort($array,'self::sortx');
  11. return $array;
  12. }
  13.  
  14. }
  15. $sort = new SortTitles;
  16. $sort->string = 'Apple ipad';
  17. $array = $sort->sort_titles($array);

猜你在找的PHP相关文章