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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With