Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move array elements to top if compared with string?

Tags:

php

mysql

I have an array $result getting from mysql as follows

    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)
        )
)

and suppose I am getting sort by value in $sort_by variable. for ex. currently,

$sort_by="Apple ipad";

so I want to move each array elements who have p_title "Apple ipad" to top.

so my 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 The New iPad (White, 64GB, WiFi)
        )
)

I am ready to edit the code either in mysql query or in php.

like image 757
Ahmed Syed Avatar asked Apr 23 '15 07:04

Ahmed Syed


1 Answers

Use usort():

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

usort($array, 'sortx');

Whenever the preceding value will contain this string, it will be pushed towards the beginning of the array.

If you want to use variable in usort() function, you need to 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);
like image 148
n-dru Avatar answered Oct 16 '22 18:10

n-dru