how to make usort work - php

$string = 'aaaaa,val1,1111; ddddd,val2,2222; gggg,val3,3333;';
$string = rtrim($string, ";");
$one = explode(';', $string);
$array = array();
$i = 0;
foreach($one as $o)
{
$two = explode(',', $o);
$name = $two[0];
$value = $two[1];
$price = $two[2];
$array[$i]['name'] = $name;
$array[$i]['value'] = $value;
$array[$i]['price'] = $price;
$i++;
}
echo '<pre>';
print_r($array);
usort($array, 'sort_by_order');
function sort_by_order ($a, $b)
{
return $a['price'] - $b['price'];
}
print_r($array);
If you copy my codes above you can see the display right away.
I am trying to make my usort() work. Sort based on price. I follow a tutorial on usort() I do not understand how it works. How does the $a and $b comes into play?

Thanks guys but I had made it work in descending order
return $b['price'] - $a['price'];

Related

Explode an array php

I had a array of list like this :
A = (a.11, b.12, c.dd)
I want to store the above array values in two different arrays like
B = (a, b, c)
C = (11,12,dd)
I tried a lot but all in vain. i am bit new to php. please help me out in this regard. Your prompt response is highly appreciated
Thanx
Hope this will help you:
$a = array("a.11,b.12,c.dd");
$b = array();
$d = array();
foreach ($a as $val)
{
$c =explode(',', $val);
foreach ($c as $v)
{
$e =explode('.', $v);
array_push($b,$e[0]);
array_push($d,$e[1]);
}
}
print_r($b);
print_r($d);
Working demo
foreach($A as $v) {
$v = explode('.', $v);
$B[] = $v[0];
$C[] = $v[1]
}
Try this,
$C = [];
$B = array_map(function($v) use(&$C){$arr = explode('.', $v); $C[] = $v[1]; return $v[0];}, $A);

PHP and ordering array items with numbers and texts

I'm using PHP. I have an array which has 1-256 items. Here is an example:
$arr[] = "(1.) Ben";
$arr[] = "Albert";
$arr[] = "Bill";
$arr[] = "(2.) Paul";
$arr[] = "(5.) Martin";
$arr[] = "(12.) Mike";
$arr[] = "(20.) John";
Question 1:
I would like to order the items alphabetically by names. So, the result should be this:
Albert
(1.) Ben
Bill
(20.) John
(5.) Martin
(12.) Mike
(2.) Paul
Question 2:
I also would like to order the items by 1) numbers and 2) names like this way:
(1.) Ben
(2.) Paul
(5.) Martin
(12.) Mike
(20.) John
Albert
Bill
How could I do the job with PHP?
It's sorting for Question 1:
<?php
$arr[] = "(1.) Ben";
$arr[] = "Albert";
$arr[] = "Bill";
$arr[] = "(2.) Paul";
$arr[] = "(5.) Martin";
$arr[] = "(12.) Mike";
$arr[] = "(20.) John";
usort($arr, function($a, $b){
$a = explode(' ', $a, 2);
$a = (count($a) > 1) ? $a[1] : $a[0];
$b = explode(' ', $b, 2);
$b = (count($b) > 1) ? $b[1] : $b[0];
return strcmp($a, $b);
});
print_r($arr); // // Print array sorted for 'Question 1'
#EDIT
And sorting for Question 2:
$arr[] = "(1.) Ben";
$arr[] = "Albert";
$arr[] = "Bill";
$arr[] = "(2.) Paul";
$arr[] = "(5.) Martin";
$arr[] = "(12.) Mike";
$arr[] = "(20.) John";
usort($arr, function($a, $b){
$a = explode(' ', $a, 2);
$b = explode(' ', $b, 2);
if(count($a) > 1 && count($b) > 1)
{
$a = str_replace(['(', ')', '.'], '', $a[0]);
$b = str_replace(['(', ')', '.'], '', $b[0]);
return $a > $b;
}
else
{
return strcmp($a[0], $b[0]);
}
});
print_r($arr); // Print array sorted for 'Question 2'
php got sort functions: asort() for sorting by value and ksort() for sorting by key.
asort($arr); // now sorted by value.
ksort($arr); // now sorted by key.
As you are using index array so u can sort alphabetically by asort() function but for the another questions u have to make a function ie. The order in which u want to sort and then apply uasort() function. Link is php.net/manual/en/functions.uasort.php check the above link u might get clear

PHP How to add two list of decimal together

public function Encrypt($message)
{
$character = str_split($message);
$encrypted = '';
foreach ($character as $character)
{
$encrypted .= (ord($character). '.');
}
return $encrypted;
}
I use that code to generate ASCII numbers. Example of the result that I generated
$a = 1.2.4.3.4.3
$b = 1.4.3.2.4.3
Then I want both together (1+1,2+4,4+3,3+2,4+4,3+3) then the result is
$c = 2.6.7.5.8.6
Is it possible to do that ? Can anyone help me please.
It's definitely possible:
$a = '1.2.4.3.4.3';
$b = '1.4.3.2.4.3';
$result = join('.', array_map(
function($a, $b) { return $a + $b; },
explode('.', $a),
explode('.', $b)
));
var_dump($result);
Explanation:
split by .
summarize
join back
Ideone: http://ideone.com/uzBVed
Perhaps you could use a function like this?
function add_number_strings($a, $b) {
$a_arr = explode('.', $a);
$b_arr = explode('.', $b);
$c_arr = array();
for ($i=0; $i<count($a_arr); $i++) {
$c_arr[] = $a_arr[$i] + $b_arr[$i];
}
return implode('.', $c_arr);
}
// Testing
$a = '1.12.9.4.3.2.1';
$b = '2.3.2.4.3.2.1';
$c = add_number_strings($a, $b);
var_dump($c); // should be 3.15.11.8.6.4.2

PHP - Return an array from loop's value in a function

For example, I have a function like this:
function loopValues()
{
$a = array('a','b','c');
foreach($a as $b)
{
$c = $b.'e';
echo $c;
}
}
How could I return its value aebece in an array like ('ae','be','ce')?
$a = array('a','b','c');
$b = array_map(function($ele) {
return $ele .= 'e';
}, $a);
See it in action
Try
function loopValues()
{
$a = array('a','b','c');
$result = array();
foreach($a as $b){
$result[] = $b.'e';
}
return $result;
}
$r = loopValues();
print_r($r);
See demo here
Simple, try this:
function loopValues()
{
$a = array('a','b','c');
$r = array();
foreach($a as $b)
{
$c = $b.'e';
$r[] = $c;
}
return $r;
}
function loopValues(){
$a = array('a','b','c');
for($i=0;$i<count($a);$i++){
$a[$i] .= 'e';
}
return $a;
}

Sort php Array by integers inside values

I'm trying to sort an array numerically but the integers are found in the middle of a value, not on the first character. Here is what my array looks like (using dummy values):
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
sort($array,1);
Output after foreach:
A25
A30
A40
AB25
AB30
AB40
B25
B30
B40
Expected output:
A25
AB25
B25
A30
AB30
B30
A40
AB40
B40
What would be the best sorting method for this? Really appreciate it, thanks!
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
usort(
$array,
function($a, $b) {
list($achar,$anum) = sscanf($a, '%[A-Z]%d');
list($bchar,$bnum) = sscanf($b, '%[A-Z]%d');
if ($anum > $bnum) {
return 1;
} elseif (($anum == $bnum) && ($achar > $bchar)) {
return 1;
}
return -1;
}
);
var_dump($array);
Have created a custom function depending on your requirement, please see below code
<?php
$array = array('A30','A25','ZZZ','A40','Rohan','B25','B30','Sakhale','B40','AB25','AB30','AB40');
$array = sortArrayByNumber($array);
var_dump($array);
/**
* #name sortArrayByNumber
* #abstract sort the entire array irrespective of the string, but the numbers into it
* also we append the elements not having any number at the end
* #author Rohan Sakhale
*/
function sortArrayByNumber($arr){
$sortedArr = array();
$tempArray = array();
$stringOnlyArray = array();
foreach($arr as $v){
$num = getNumberFromString($v);
/**
* If no number found, append it into stringOnlyArray
*/
if($num == ''){
$stringOnlyArray[] = $v;
continue;
}
if(!isset($tempArray[$num])){
$tempArray[$num] = array();
}
$tempArray[$num][] = $v;
}
$tempArrayKeys = array_keys($tempArray);
sort($tempArrayKeys);
foreach($tempArrayKeys as $key){
sort($tempArray[$key]);
$sortedArr = array_merge($sortedArr, $tempArray[$key]);
}
if(count($stringOnlyArray) > 0){
sort($stringOnlyArray);
$sortedArr = array_merge($sortedArr, $stringOnlyArray);
}
return $sortedArr;
}
/**
* #str - String param which tend to have number
*/
function getNumberFromString($str){
$matches = null;
preg_match_all('!\d+!', $str, $matches);
if(!is_null($matches) and is_array($matches)){
if(isset($matches[0][0])){
return $matches[0][0];
}
}
return '';
}
?>
Here sort by number method is trying to firstly identify the number's in your string and maintain a separate array of it based on the keys, later we sort in ascending order every key's of number and then we finally merge it into sorted array
You can use user defined function with usort to achieve it
<?php
function mySort($a,$b) {
$numA = '';
$strA = '';
$numB = '';
$strB = '';
for($i=0;$i<strlen($a); $i++) {
if(is_numeric($a[$i])) {
$numA .= (string)$a[$i];
}
else {
$strA .= $a[$i];
}
}
for($i=0;$i<strlen($b); $i++) {
if(is_numeric($b[$i])) {
$numB .= (string)$b[$i];
}
else {
$strB .= $b[$i];
}
}
$numA = (int)$numA;
$numB = (int)$numB;
if($numA>$numB) {
return true;
}
elseif($numA<$numB) {
return false;
}
else {
if(strcmp($strA,$strB)>0) {
return true;
}
else {
return false;
}
}
}
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
var_dump($array);
usort($array,'mySort');
var_dump($array);
?>
Here's a stable sort, the result is: "A25" "B25" "AB25" "A30" "B30" "AB30" "A40" "B40" "AB40" .
function getNum($str)
{
preg_match ( '/(\d+)$/', $str, $match );
return intval ( $match [1] );
}
function stableSort($arr)
{
$newArr = array ();
foreach ( $arr as $idx => $ele )
{
$newArr [] = array (
'idx' => $idx,
'val' => $ele
);
}
usort ( $newArr,
function ($a, $b)
{
$d = getNum ( $a ['val'] ) - getNum ( $b ['val'] );
return $d ? $d : $a ['idx'] - $b ['idx'];
} );
$sortArr = array ();
foreach ( $newArr as $ele )
{
$sortArr [] = $ele ['val'];
}
return $sortArr;
}
var_dump ( stableSort ( $array ) );
U can use various kinds of ways to sort arrays in PHP. PHP has some good ways build in to do sorting on arrays. In this case I agree with Mark Baker, however I would recommend a preg_replace to get the numeric value of your strings.
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
function cmp($a, $b)
{
$v1 = preg_replace("/[^0-9]/", "", $a);
$v2 = preg_replace("/[^0-9]/", "", $b);
if ($v1 == $v2) {
return 0;
}
return ($v1 < $v2) ? -1 : 1;
}
usort($array, "cmp");
var_dump($array);
Look into the PHP information about sorting arrays, php.net/usort and various others.

Categories