PHP - Sort Two Arrays The Same Way - php

I have two different arrays. One array, a, for a list of people. My other array, b, for a list of their ages. I go to sort b by number and then reverse it so it goes in descending order. I got to this part okay.
How do I sort a (a list of people's names) so that the same values are still paired up with the sorted list?
Example:
a contains Bob, Sue, Phil, and Jenny respectively
b contains 15, 12, 13, and 13 respectively.
I want my outcome to be:
a contains Bob, Jenny, Phil, and Sue respectively
b contains 15, 13, 13, and 12 respectively

http://php.net/manual/en/function.array-multisort.php
using example #1 in the reference:
$a = array('Bob', 'Sue', 'Phil', 'Jenny');
$b = array(15, 12, 13, 13);
array_multisort($a, $b);
print_r($a);
> Array
(
[0] => Bob
[1] => Jenny
[2] => Phil
[3] => Sue
)
print_r($b);
> Array
(
[0] => 15
[1] => 13
[2] => 13
[3] => 12
)

Why not just use:
$arr = array('Bob'=>15,'Sue'=>12,'Phil'=>13,'Jenny'=>13);
Then you can sort smoothly.

Related

How to sort an multiple multidimension array in PHP [duplicate]

I have two different arrays. One array, a, for a list of people. My other array, b, for a list of their ages. I go to sort b by number and then reverse it so it goes in descending order. I got to this part okay.
How do I sort a (a list of people's names) so that the same values are still paired up with the sorted list?
Example:
a contains Bob, Sue, Phil, and Jenny respectively
b contains 15, 12, 13, and 13 respectively.
I want my outcome to be:
a contains Bob, Jenny, Phil, and Sue respectively
b contains 15, 13, 13, and 12 respectively
http://php.net/manual/en/function.array-multisort.php
using example #1 in the reference:
$a = array('Bob', 'Sue', 'Phil', 'Jenny');
$b = array(15, 12, 13, 13);
array_multisort($a, $b);
print_r($a);
> Array
(
[0] => Bob
[1] => Jenny
[2] => Phil
[3] => Sue
)
print_r($b);
> Array
(
[0] => 15
[1] => 13
[2] => 13
[3] => 12
)
Why not just use:
$arr = array('Bob'=>15,'Sue'=>12,'Phil'=>13,'Jenny'=>13);
Then you can sort smoothly.

Is this normal behaviour in php arrays? Array size get shortened when using numbered indexes out of order

So I'm learning Php, so as I was messing around with arrays to see how they work, I stumbled into this when I made two arrays.
$TestArray1 = array( 1 => 1, "string" => "string", 24, "other", 2 => 6, 8);
$TestArray2 = array( 6 => 1, "string" => "string", 24, "other", 1 => 6, 8);
But when I print them out with print_r() this is what I get (this also happens with var_dump by the way)
Array ( [1] => 1 [string] => string [2] => 6 [3] => other [4] => 8 )
Array ( [6] => 1 [string] => string [7] => 24 [8] => other [1] => 6 [9] => 8 )
As far as I can tell, by putting the two in the second array it overwrites the next possible spot with no key and then keeps going, shortening the array. So I thought that meant that if I use a 1 it would put it at the start but that does not happen either.
Is this normal or is there something wrong with my php installation?
Im using Ampps in windows 10 with php 7.3.
Thanks in advance
Good question.
What's happening is that when determining automatic numeric indexes, PHP will look to the largest numeric index added and increment it (or use 0 if there are none).
The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.
What's happening with your first array is that as it is evaluated left-to-right, 24 is inserted at index 2 because the last numeric index was 1 => 1.
Then when it gets to 2 => 6, it overwrites the previous value at index 2. This is why 24 is missing from your first array.
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.
Here's a breakdown
$TestArray1 = [1 => 6]; // Array( [1] => 6 )
// no index, so use last numeric + 1
$TestArray1[] = 24; // Array( [1] => 6, [2] => 24 )
$TestArray1[2] = 6; // Array( [1] => 6, [2] => 6 )
When you manually add numeric indexes that are lower than previous ones (ie $TestArray2), they will be added as provided but their position will be later.
This is because PHP arrays are really maps that just pretend to be indexed arrays sometimes, depending on what's in them.
References are from the PHP manual page for Arrays

How does the sort_flag works for sorting the array? [duplicate]

This question already has an answer here:
PHP, sort, sort_flags
(1 answer)
Closed 2 years ago.
I have an array to sort as
$numbers = array(24, 19, 3, 16, 56, 8, 171);
sort($numbers, SORT_STRING);
print_r($numbers);
And thus when i sort the array i get the result as
(
[0] => 16
[1] => 171
[2] => 19
[3] => 24
[4] => 3
[5] => 56
[6] => 8
)
How does the SORT_STRING works can anybody explain it to me?
SORT_STRING will compare character by character as in a word. So letter A is "higher" (or lower, your choice) than B, B > C.
1 > 2, 2 > 3, 11 > 12 and so on.
So in your case, when comparing 24 with 19, it will compare 1 with 2 and then order.
As a second example, when comparing 19 with 16, first will compare 1 with 1, which is equal, then compare 9 with 6, making 6 (and 16) a higher order.
More info here: PHP, sort, sort_flags
If you want to dig deeper, this is the link for the PHP source code.
This is the line where it choices the sort algorithm depending on the sort flag:
https://github.com/php/php-src/blob/50765075db6b6d5a9597589601c59f743f6ee9c8/ext/standard/array.c#L502
And here where it execute the comparison/sort:
https://github.com/php/php-src/blob/50765075db6b6d5a9597589601c59f743f6ee9c8/ext/standard/array.c#L207
And then it will call a zend operator:
https://github.com/php/php-src/blob/5430a466ff31422b436df076581d8345531db975/Zend/zend_operators.c
The SORT_STRING compare items as strings. You can find more detail here: https://www.php.net/manual/en/function.sort.php
A simple example is when you sort your files or directories on you computer: the sorting is alphabetical order.
This works as an ascending numeric values for the first digits(as 1 in 16) of all the numbers and after finishing them all,the pointer goes towards the digit next to it (as 6 in 16) and this is how it works so basically it arranges the digits from the left most digit and then goes on arranging them by the preceeding ones(right).
For example: comparing between 16 and 171
As both the numbers have their left-most digits as 1 it sorts it numbers based on their next digits(the right ones).
And thus by following the rule you get an result array as
(
[0] => 16
[1] => 171
[2] => 19
[3] => 24
[4] => 3
[5] => 56
[6] => 8
)

Merge 2 arrays in random positions

How would someone merge 2 arrays where $_array_1 is scattered but $_array_2 maintains its original order globally?
I have 2 arrays
$_array_1 = array( a, b, c );
$_array_2 = array( 1, 2, 3, 4, 5, 6 );
$_merged_array = array( c, 1, a, 2, 3, 4, 5, b, 6 );
I know this must be possible but don't have a clue where to start. What is the most efficient method and cleanest?
My interpretation of your post is: Insert every value of array 1 on a random position in array 2. This can be achieved with the following code:
$_array_1 = array( 290, 188, 519 );
$_array_2 = array( 213, 702, 231, 173, 632, 711 );
foreach($_array_1 as $val) {
array_splice($_array_2, rand(0, count($_array_2)), 0, $val);
}
print_r($_array_2); // For example: Array ( [0] => 519 [1] => 213 [2] => 290 [3] => 702 [4] => 231 [5] => 173 [6] => 632 [7] => 188 [8] => 711 )
I don't see how the end result makes sense, but here's what you can do:
Copy the second array in the merged array,
Insert the values in the first array at random positions in the merged array using $insert_position = mt_rand(0, count($merged_array)).
Note that it's not an error that I didn't do count($merged_array) - 1, because we also want the numbers to be randomly added at the end of the array.

Best way to iterate to a part of an array based on value?

I have an php-array like this:
$students = array(
array(1, 'James', 'Brown', 10, 50),
array(2, 'John', 'Doe', 10, 40),
array(3, 'Adam', 'Works', 10, 40));
Where the columns represent id, first name, last name, category, and level. As example I use three rows... in practice I use many more.
Now I need to group print the results based on column (category or level) and a specific value. For example, I want to print (echo) all students in category 10. I can loop through each record and check the category; if 10 then print. The same applies for level 40. Loop through the whole set again and check the level; if 40 then print.
With an eye on performance, is there a smarter way to achive this? For example, first sort or filter?
I could choose to query the database many times but I doubt if this is the best way. I guess manipulating the array is better.
Thanks for your support!
The most straightforward way to do this is with the array_filter() function. But if these values come from a database, you're probably better off writing better queries.
$ cat array-filter.php
<?php
$students = array(
array(1, 'James', 'Brown', 10, 50),
array(2, 'John', 'Doe', 10, 40),
array(3, 'Adam', 'Works', 10, 40));
$level_40 = array_filter($students, function($a) {return $a[4]==40 ? true : false;});
print_r($level_40);
?>
$ php array-filter.php
Array
(
[1] => Array
(
[0] => 2
[1] => John
[2] => Doe
[3] => 10
[4] => 40
)
[2] => Array
(
[0] => 3
[1] => Adam
[2] => Works
[3] => 10
[4] => 40
)
)
The callback function just compares the fifth column to the integer literal 40. The fifth column has index 4, not 5, hence the expression $a[4]==40 ?.
If you're getting this data from a database, you're probably better off writing better SQL. To get all the students whose level is 40, you'd write something like
select *
from students
where level = 40
order by student_id;
The result set will contain exactly the right rows, so you don't need to filter them. And they'll be in exactly the right order, so you don't need to sort them.

Categories