php array sort in foreach - php

I am trying to order an array produced by a foreach loop, here is my code:
$lowestvar = array();
foreach ($variations as $variation){
$lowestvar[] = $variation['price_html'];
}
I am then using array_multisort like this:
array_multisort($lowestvar, SORT_ASC);
print_r($lowestvar);
This works for the first looped item with a output of:
Array ( [0] => £10.00 [1] => £15.00 )
But the second array in the loop looks like this:
Array ( [0] => £10.00 [1] => £5.00 )
Any ideas on where i am going wrong?

You're sorting STRINGS, which means that 10 < 5 is true. Remember that string sorting go char-by-char, not by "entire value".

You can use usort() as like in the following example
function cmp($a1, $b1)
{
$a=str_replace('£','',$a1);
$b=str_replace('£','',$b1);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array('£10.00','£5.00');
usort($a, "cmp");
print_r($a);
Output
Array
(
[0] => £5.00
[1] => £10.00
)

Related

Flatten 2D Array Into Separate Indexed Arrays

I have the array:
$total =array();
Array (
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
)
)
I need to dynamically change each array into an indexed array for a Cartesian function.
Here is how I need the code to look for the function to work correctly:
$count = cartesian(
Array(1,3),
Array(6,7,8),
Array(9,10)
);
Any help would be greatly appreciated! I have tried flattening, looping, using array_values, using just the array itself and I keep falling short.
Thanks
Nick
function cartesian() {
$_ = func_get_args();
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}
$count = call_user_func('cartesian', array($total));
print_r($count);
Your arrays already look exactly the way you want them to. array(1,3) is the same as array(0 => 1, 1 => 3) and both are an array with the value 1 at key 0 and 3 at key 1. Exactly what the debug output shows you.
It seems you just need to pass them as separate arguments to the function. E.g.:
cartesian($total[0], $total[1], $total[2])
For dynamic lengths of arrays, do:
call_user_func_array('cartesian', $total)
I believe that your $total array is multi-dimensional array with numeric indexed. So yo can try like this
$count = cartesian($total[0], $total[1], $total[2]);

PHP - Sort arrays by keys and values

Hello how to sort arrays by keys and values too... so if user input this value
$input = array(0,1,0,2,0);
then the result should be like this since they're the same input they should maintain their keys too...
Array
(
[0] => 0
[2] => 0
[4] => 0
[1] => 1
[3] => 2
)
not like this... the keys is jumbled and I really that key to work on my project of FCFS Scheduling.
Array
(
[4] => 0
[0] => 0
[2] => 0
[1] => 1
[3] => 2
)
btw I used asort. someone help me how to fix this?
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(0,1,0,2,0);
usort($a, "cmp");
foreach ($a as $key => $value) {
echo " $value\n";
}
Stable sort would help here. But php don't have any stable sorting functions since 4.1.
But you can use uksort + closure.
$input = array(0,1,0,2,0);
$cmp = function($a, $b) use($input){
if($input[$a] > $input[$b]){return 1;}
elseif($input[$a] < $input[$b]){return -1;}
elseif($a>$b){return 1;}
elseif($a<$b){return -1;}
return 0;
};
uksort($input, $cmp);
print_r($input);
https://eval.in/145923
Or shorter version
$cmp = function($a, $b) use($input){
return (($input[$a]-$input[$b])?:($a-$b));
};
Simple use the sort function
$input = array(0,1,0,2,0);
sort($input);
Result:-
Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 1
[4] => 2
)

Alphabetically sort the array

Array
(
[0] => Jane Smith
)
Array
(
[0] => John Paul
)
Array
(
[0] => Jennifer
)
Array
(
[0] => Paolo
)
Array
(
[0] => Delilah
)
foreach($name as $a){
print_r($a);
}
Is it possible to alphabetically arrange this array?
How can i use the sort() in here?
Try this :
$array = your array
$result = call_user_func_array('array_merge', $array);
sort($result);
echo "<pre>";
print_r($result);
Try this:
<?php
$ar1 = array("Jane Smith", "John Paul ", "Jennifer", "Paolo","Delilah");
function alphasort($a, $b) {
if ($a['name'] == $b['name']) {
return 0;
}
return ($a['name'] < $b['name']) ? -1 : 1;
}
usort ($ar1,'alphasort');
echo '<pre>';
print_r($ar1);
?>
Result:
Array
(
[0] => Delilah
[1] => Jane Smith
[2] => Jennifer
[3] => John Paul
[4] => Paolo
)
Try like
$array = your array;
asort($array);
Try this LINK
Since it looks like you're trying to sort an array of arrays of strings instead of an array of strings, you cannot use sort().
$array = array(array('Jane Smith'), array('John Paul'), array('Jennifer'));
function cmp($a, $b)
{
$a = $a[0];
$b = $b[0];
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
usort($array, "cmp");
foreach($name as $a){
print_r($a);
}
Example code based on this documentation.
Take a look at here for all kinds of PHP array sorting. But for your specific question after doing array_merge() on all you arrays to have a single onw, either sort() or asort() should work just like this:
$all=array();
foreach($name as $a){
$all=array_merge($all, $a);
}
sort($all);
print_r($all);
OR
$all=array();
foreach($name as $a){
$all=array_merge($all, $a);
}
asort($a);
print_r($a);

Sort array by sub array

I have array:
$array = array(array('2012-12-12', 'vvv'), array('2012-12-14', 'df'),array('2012-12-10', 'vvv'),array('2012-12-11', 'vvv'));
Array
(
[0] => Array
(
[0] => 2012-12-12
[1] => vvv
)
[1] => Array
(
[0] => 2012-12-14
[1] => df
)
[2] => Array
(
[0] => 2012-12-10
[1] => vvv
)
[3] => Array
(
[0] => 2012-12-11
[1] => vvv
)
)
http://codepad.org/gxw2yKMU
is possible to sort this with dates DESC? For this example should be:
$array[1] //2012-12-14
$array[0] //2012-12-12
$array[3] //2012-12-11
$array[2] //2012-12-10
For me the best way is use embedded functions for PHP, but how? :)
You can use usort with a custom function. If you're on PHP < 5.3 you'll need a named function rather than, as I have, an anonymous one.
$array = array(
array('2012-12-12', 'vvv'),
array('2013-12-14', 'df'),
array('2012-12-14', 'df'),
array('2012-12-10', 'vvv'),
array('2012-12-11', 'vvv')
);
usort($array, function($a, $b) {
if ($a[0] == $b[0]) return 0;
return ($a > $b) ? -1 : 1;
});
print_r($array);
You should be able to use usort
usort( $array, 'sortFunction' );
function sortFunction( $a, $b ) {
if( $a[0] == $b[0] )
return 0;
return ( $a[0] > $b[0] ? return -1 : 1 );
}
You can use array_multisort() :
foreach ($array as $key => $row) {
$dates[$key] = $row[0];
}
array_multisort($dates, SORT_DESC, $array);
First, you put out all dates in a new array. Then, array_multisort() will sort the second array ($array) in the same order than the first ($dates)

Merge two sorted arrays and the resulting array should also be sorted

Let's say you have two arrays of arrays with the same structure but different count of arrays in them:
$arr1 = array(array(1,"b"), array(2,"a"), array(5,"c"));
$arr2 = array(array(3,"e"));
Now, the data in the $arr1 and $arr2 is sorted, and now what I would like it to merge these two arrays, so I did this:
$res = array_merge($arr1, $arr2);
And then I get an output like this:
1-b
2-a
5-c
3-e
But, I would like to have a sorted $res also like this:
1-b
2-a
3-e
5-c
I wonder if there's a function in PHP to do this automatically, without me having to write my own function? Or, please advise me on which is the best approach for this if I want to (later on) add sorting by the next parameter so the output would be like this
2-a
1-b
5-c
3-e
Thank you for all your help.
You can first merge the arrays and then sort the final array.
You are probably looking for a multi-sort function. I usually use this function (I found this functions somewhere on the internet years ago, credits go to the original author):
/*
* sort a multi demensional array on a column
*
* #param array $array array with hash array
* #param mixed $column key that you want to sort on
* #param enum $order asc or desc
*/
function array_qsort2 (&$array, $column=0, $order="ASC") {
$oper = ($order == "ASC")?">":"<";
if(!is_array($array)) return;
usort($array, create_function('$a,$b',"return (\$a['$column'] $oper \$b['$column']);"));
reset($array);
}
You can use it like this:
array_qsort2($res, 0, "ASC");
Why not simply call ksort($res) after your array_merge?
Since php v5.3 you can use anon functions in a more natural manner,
<?php
$arr1 = array(array(1,"b"), array(2,"a"), array(5,"c"));
$arr2 = array(array(3,"e"));
$res = array_merge($arr1, $arr2);
usort($res, function($a,$b) {
// php7
// return $a[0] <=> $b[0];
if ($a[0] == $b[0]) return 0;
return $a[0] < $b[0] ? -1 : 1;
});
print_r($res);
output
Array
(
[0] => Array
(
[0] => 1
[1] => b
)
[1] => Array
(
[0] => 2
[1] => a
)
[2] => Array
(
[0] => 3
[1] => e
)
[3] => Array
(
[0] => 5
[1] => c
)
)
You can use below function to merge two sorted arrays without array_merge() or sort().
<?php
$arr1 = [1,2,5,7,10,20,36,70,82,90];
$arr2 = [4,6,10,15,65,85,90,100];
function shortt($array1,$array2){
$array1_count = count($array1);
$array2_count = count($array2);
while ($array1_count || $array2_count)
{
$array1_empty = $array1 == [];
$array2_empty = $array2 == [];
if (!$array1_empty && !$array2_empty)
{
if (current($array1) < current($array2))
{
$array3[] = array_shift($array1);
$array1_count--;
}
else
{
$array3[] = array_shift($array2);
$array2_count--;
}
}
elseif (!$array1_empty)
{
$array3[] = array_shift($array1);
$array1_count--;
}
elseif (!$array2_empty)
{
$array3[] = array_shift($array2);
$array2_count--;
}
}
return $array3;
}
$newarr = shortt($arr1,$arr2);
print_r($newarr);
?>

Categories