how php array_multisort work? - php

i have some problem to understand array_multisort
See how it sorts when two values are the same:
$a1=array("Dog","Dog","Cat");
$a2=array("Pluto","Fido","Missy");
array_multisort($a1,$a2);
print_r($a1);
print_r($a2);
The output of the code above will be:
Array ( [0] => Cat [1] => Dog [2] => Dog )
Array ( [0] => Missy [1] => Fido [2] => Pluto )
let me know why Missy comes first, if you do by ascending it must be
Array ( [0] => Fido, [1] => Missy, [2] => Pluto )
for descending vise versa
also see this
With sorting parameters:
$a1=array("Dog","Dog","Cat");
$a2=array("Pluto","Fido","Missy");
array_multisort($a1,SORT_ASC,$a2,SORT_DESC);
print_r($a1);
print_r($a2);
The output of the code above will be:
Array ( [0] => Cat [1] => Dog [2] => Dog )
Array ( [0] => Missy [1] => Pluto [2] => Fido )
but Array ( [0] => Missy [1] => Pluto [2] => Fido ) not at SORT_DESC is some type of mixed up.
can some one explain me how the array_multisort is working, so that i can understand how it's working.

Well, you're sorting the arrays in a similar way to programs like Excel. Each array corresponds to a column.
First, all arrays are sorted by the first array given. If there are identical values, those affected are sorted by the second array given. If there are again equal values, the third array is used, etc.
Or in other words: The arrays are sorted using all arrays, but beginning on the right (if you assume it really sorts by all columns once).
For your particular example (the second one):
At first you want to sort in ascending order, so Cat will be first. Therefore the last array element will be moved to the first position in both arrays. The other two elements, Dog are equal. This causes the function to look at the next array. It's told to sort this array in descending order, so Pluto comes first. In this case this leads to the result that the elements aren't moved at all (as their order is correct already).

The entries in the second array corresponding to the identical entries in the first array.

If you look at the documentation and the first example, you'll notice that this is the expected behavior.
With two arguments, both arrays: the first array is sorted; the second array will have its corresponding values re-arranged and sorted if the corresponding values in first column tie. As for your example, think of it as you're doing a SQL ORDER BY Animal, Name:
Cat comes first
The two Dogs have a tie so Fido comes first because Fido < Pluto

Related

Operation at strings and arrays

I wish to ask about operations over arrays in php.
I'm capturing two cells from one table in database, which are holding strings formatted like "1;3;6;" and whole second table - it has numbers in first column and names in second. Im dividing strings from first table into two arrays using explode() function, and second table into next two arrays with column per array. Therefore, when print_r() is used over those three arrays, I will see:
error_reporting(E_ALL); ini_set('display_errors', 1);
first table
"amount" string transformed into array called $ship_storage_parted_amount Array
(
[0] => 5
[1] => 10
[2] =>
)
"ware id" string transformed into array called $ship_cargo_bay_parted Array
(
[0] => 1
[1] => 2
[2] =>
)
second table transfomed into two arrays $ware_id and $ware_name
table contains 7 rows at all
Array
(
[0] => Array
(
[ware_id] => 1
[name] => Energized energy cell
)
[1] => Array
(
[ware_id] => 2
[name] => Depleted energy cell
)
[2] => Array
(
[ware_id] => 3
[name] => Vegetables
)
[3] => Array
(
[ware_id] => 4
[name] => Meat
)
)
I want to achieve next thing: showing at website appropriate equal names from second table according to their IDs with conjunction of what is stored in first table.
Therefore, it should look like:
Energized energy cell x5
Depleted energy cell x10
When I've tryied to show them like that:
echo $ware_name[$ship_cargo_bay-1]." x".$ship_storage_parted_amount[$ware_position];
it resulted in such output:
Energized energy cell x
where $ship_cargo_bay contains all captured string "ware id" and $ware_position was amount counter. Amount counter pointed at 3rd array element which is empty; but when I reorganized printing with for()
for($i=0;$i}lowerthan{$ware_counter;$i++)
{echo $ware_name[$ship_cargo_bay_parted[$i]]." x".$ship_storage_parted_amount[$i];}
I've got now
x5 x10 x x
And my poor knowledge ends here. As I know, first attempt of printing shall not work at all, but why I've got such output in second attempt is over my understanding.
Finally found reasons, where I made mistakes. After carefully checking names of each single variable, printing what exactly everything contains, I found that Ive somehow mispelled variable names.
for($i=1;$i<$ware_counter;$i++)
{
echo $ware_name[$ship_storage_parted[$i]]." x ".$ship_storage_parted_amount[$i]."<br/>";
}
This few lines gives exactly what Ive needed. Therefore Im putting it here - maybe someone will encounter similar problem.

2 or more arrays from a list

I am quite not able to get the logic for my requirement.
Lets consider I have an array
Array
(
[0] => 1
[1] => 1
[2] => 2
[3] => 1
[4] => 3
[5] => 3
)
I would like to split the below array on the basis if the array element matches its previous element.
i.e in the above example value at [1] matches the value at [0]. Hence put it into the same array as [0]. Now check if the value at [2] matches the value at [1] if it matches put it into the same array, if not put it into a different array. The process continues.
Below is an example of the desired outpout.
Array
(
[0] => 1
[1] => 1
)
Array
(
[0] => 2
)
Array
(
[0] => 1
)
Array
(
[0] => 3
[1] => 3
)
Thanks for your help in advance.
Justin
you can obtain that result in a loop checking on previous element. the output can be an array of arrays! (or anything you would prefer.. do your thing here)
$array1 = array(1, 1, 2, 1, 3, 3);
$output_array=array();
$previous_value="";
$output_array_index=0;
foreach ($array1 as $value) {
if($value != $previous_value){
$output_array_index+=1;
}
$output_array[$output_array_index][]=$value;
$previous_value=$value;
}
print_r($output_array);
so, let me know if you need more pointers! array logic is fun, and php will let you do alot, out of the box. though this specific need is not covered, have a look when you have a minute # the manual, it'll save you time in the future, guarantee http://php.net/manual/en/ref.array.php
This question is a bit confusing but doesn't sound too difficult to implement if I'm understanding it correctly. All you need to do is have a temporary array (or array list) that checks user input. If that user input happens to be the same as the previous input (you can keep a counter variable and check to see if ArrayList.get(counter) == ArrayList.get(counter-1)). Keep adding things to this temporary arrayList and once you have a number that is different, just iterate through the arraylist and add it to a new array.
Another question you have to consider is how you are going to store all these arrays. For that you may want to create an ArrayList containing Arrays. That way after you find user input that is different from the previous input you can just use the toArray method provided with the ArrayList class and add it to the ArrayList containing all of your separate Arrays!
Hope this helps!

PHP - Why doesn't array_multisort function sort correctly?

please view the following code with 2 arrays. i use multisort function with sort flags for ascending and numeric then display. as you can see in the output that array 2 starts with 100 when it should be last. please explain what is causing this and how to sort it correctly. thank you.
<?php
$array1 = array(1,7,10,6);
$array2 = array(100,20,25,10);
array_multisort($array1, SORT_ASC, SORT_NUMERIC, $array2);
print_r($array1);
echo "<br>";
print_r($array2);
?>
output:
Array ( [0] => 1 [1] => 6 [2] => 7 [3] => 10 )
Array ( [0] => 100 [1] => 10 [2] => 20 [3] => 25 )
Ah, yes, array_multisort is a bit tricky to understand the first time round.
Basically the sort is lexicographical, a fancy word meaning that the first array is sorted and the second arrays elements are ordered according to the first array.
Look at your first (output) array and see the order and map it to the initial second array and you'll see whats happening.
So the second array you take the 1st, 4th , 2nd and 3rd elements.
If you just want plain sorting for multiple arrays then just do them one by one or over a loop.

Sort a multidimensional array by

I want to sort the following multidimensional array by several keywords - let me explain in a simple way.
this is how the parts in my multidimensional array look like
[template] => Array
(
[0] => Array
(
[KeyA] => 123
[KeyB] => ABC
[KeyC] => #FFFFF
[custom] => Array
(
[0] => Array
(
[value] => bla
[var] => 2
)
[1] => Array
(
[value] => c1
[var] => 5
)
)
)
)
there are tons of multidimensional arrays in that template array and I want them now to sort for example by KeyC (#00000 first prio, #FFFFFF second prio, #333333 third prio) and then by KeyA alphabetic.
How to do that ?
PHP has several functions that deal with sorting arrays and the logic behind array sorting are:
Some sort based on the array keys, whereas others by the values: $array['key'] = 'value';
Whether or not the correlation between the keys and values are maintained after the sort, which may mean the keys are reset numerically (0,1,2 ...)
The order of the sort: alphabetical, low to high (ascending), high to low (descending), numerical, natural, random, or user defined
If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).
Note: All of these sort functions act directly on the array variable itself, as opposed to returning a new sorted array.
The main functions of sorting are described http://www.php.net/manual/en/array.sorting.php and for creating custom sorting you have to tricks best suitable to yourself.

How to reset indexes in array_diff result?

I have two arrays: Array ( [0] => 2 [1] => 3 ) and Array ( [0] => 2 ).
I want to get the value, which is not in second array. So I have used the array_diff function but my result will get Array ( [1] => 3 )
Actually this is the result. But a small problem here, its position is (key) 1. I want the result in to a new array starts from 0th position, i.e., Array ( [0] => 3 ).
How can I achieve this?
you can use array_values(array_diff($arr1, $arr2)); if order doesn't matter
You should run array_values() on the result and this would give you a new array with indexes starting at 0.
This is a known shortcoming of array_diff(), check the php docs.

Categories