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
Related
$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'];
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
I have two valriables in
$a="1:2:3";
$b="1:3:4:5";
Is there any simple method to add 4 and 5 in variable $a. Means i want the value of variable to be
$a="1:2:3:4:5"
A one line solution:
$result = implode(':', array_unique(array_merge(explode(':', $a), explode(':', $b))));
An even shorter one would be:
$result = implode(':', array_unique(array_merge(explode(':', "$a:$b"))));
$a2 = explode(":" , $a);
$b2 = explode(":" , $b);
foreach($b2 as $val)
{
if(in_array($val , $a2))
//do what you want
}
try this
$a="1:2:3";
$b="1:3:4:5";
$a = explode(':', $a);
$b = explode(':', $b);
$c = array_unique(array_merge($a,$b));
$a = implode(':', $c);
echo $a;
I notice that $a is ordered, so you can apply sort to the new array
$sort = SORT_NUMERIC;
$a = implode(':',array_uniqe(array_merge(explode(':',$a),explode(':',$b)),$sort));
See array_unique to other possible sorts.
I have a php array as follows,
<?php
$arr = array('op'=>'pqr', 'ab'=>'xyz', 'mn'=>'abcd');
?>
How to set xyz value as first element with minimum loop,if the value exist.
Expected Result
<?php
$arr = array('ab'=>'xyz', 'op'=>'pqr','mn'=>'abcd');
?>
$ab = $array['ab'];
unset($array['ab']);
$array = array('ab' => $ab) + $array;
If the key itself is unknown, find it first:
$key = array_search('xyz', $array);
$tmp = $array[$key];
unset($array[$key]);
$array = array($key => $tmp) + $array;
Or go with a sort:
uasort($array, function ($a, $b) {
if ($a == 'xyz') return -1;
if ($b == 'xyz') return 1;
return 0;
});
<?php
$arr = array('op'=>'pqr', 'ab'=>'xyz', 'mn'=>'abcd');
ksort($arr);
echo '<pre>';
print_r($arr);
I'm trying to sort several arrays in numerical order based on the value in their first key:
$array1[0] = '1';
$array1[1] = 'content';
$array1[2] = 'more content';
$array3[0] = '3';
$array3[1] = 'content';
$array3[2] = 'more content';
$array4[0] = '4';
$array4[1] = 'content';
$array4[2] = 'more content';
$array2[0] = '2';
$array2[1] = 'content';
$array2[2] = 'more content';
$arrays = array($array1, $array3, $array4, $array2);
foreach ($arrays as $array) {
echo $array[0] . ' ' . $array[1] . ' ' . $array[2] . '<br>';
}
That outputs the arrays in a '1, 3, 4, 2' sequence, I need them to be output thusly: '1, 2, 3, 4'. Not sure how or even if to use the ksort/asort/array_multisort functions here.
You will need a custom comparison function that you then can use with usort or uasort:
function cmp($a, $b) {
return intval($a[0]) - intval($b[0]);
}
usort($arrays, 'cmp');
As of PHP 5.3 you could also use an anonymous function for the comparison function:
usort($arrays, function($a, $b) { return intval($a[0]) - intval($b[0]); });
You could also use array_multisort, create an array of the keys that are to be sorted first and use it to sort the array items itself:
$keys = array();
foreach ($arrays as $array) $keys[] = intval($array[0]);
array_multisort($keys, $arrays);
Doing this prevents calling the comparing function for each pair of values that is compared as only the key values are compared.
Using usort you can specify your own sorting criteria on an array. This is an idea of how you could achieve what you ask for
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return (intval($a[0]) < intval($b[0])) ? -1 : 1;
}
usort($arrays, "cmp");