I looked at different options how to sort arrays. But somehow none of the given PHP commands suit my purpose.
Example - I have an array like this :
Array
(
[abc] => Array
(
[2] => 2
[3] => 3
[5] => 5
)
)
But I want to change the array to
[0] => 2
[1] => 3
[2] => 5
In other words I want to remove all keys - sort all values from LOW to HIGH and then just give em the keys from zero to X
It's much easier to work with such an array if you want to use some loops like (for, while, etc.)
Just use sort and array_values.
<?php
$array = array(
'abc' => array(
2 => 2,
5 => 5,
3 => 3,
),
);
sort($array['abc']);
$array = array_values($array['abc']);
print_r($array);
I've popped up an example at http://3v4l.org/51naW
Related
I have an array like this
Array
(
[0] => Array
(
[0] => space
[1] => Venus
[2] => NASA
[3] => apple
)
[1] => Array
(
[0] => link1
[1] => link2
[2] => link3
[3] => link4
)
)
I want to sort it, case INsensitively, by the [0] term. How can I do this? All answers I've found show how to do this only if the array has keynames.
If that's not clear, I want this:
Array
(
[0] => Array
(
[0] => apple
[1] => NASA
[2] => space
[3] => Venus
)
[1] => Array
(
[0] => link4
[1] => link3
[2] => link1
[3] => link2
)
)
If it's easier with keynames, or it can't be done unless there are keynames (which I doubt), how can I modify my original array to contain names "keywords" for [0] and "links" for [1]?
Many thanks.
This code merges the multiple dimension version back into a key/value single array which makes it easy to sort, and then optionally brings it back to multiple dimensions. Demo here: https://3v4l.org/CStsS
$data = [
['space', 'Venus', 'NASA', 'apple'],
['link1', 'link2', 'link3', 'link4'],
];
// Convert the multiple dimensional array to avsingle
$merged = array_combine(...$data);
// Sort by key
uksort($merged, fn($a, $b) => strcasecmp($a, $b));
var_dump($merged);
// If it needs to be converted back to a multiple dimension array
$data = [
array_keys($merged),
array_values($merged),
];
var_dump($data);
EDIT
Another answer was provided by #lukas.j that used the built-in array_multisort function, but has since been deleted. In theory, being a native function, that code might be more performant for large arrays, and, with a couple of optimizations, it also skips the intermediary variables. I personally avoid multiple dimension arrays whenever possible (personal preference) so I’ve never used that function, but I think it works here perfectly.
$arr = [
[ 'space', 'Venus', 'NASA', 'apple' ],
[ 'link1', 'link2', 'link3', 'link4' ]
];
array_multisort($arr[0], SORT_NATURAL | SORT_FLAG_CASE, $arr[1]);
print_r($arr);
Demo here: https://3v4l.org/saI1C
I am trying to create little app that randomly selects a number of chords/notes from a scale but I am having trouble with using the array_rand to get those random values from an array.
I have an array called $scale that looks like this:
Array
(
[0] => f#
[1] => g#
[2] => a#
[3] => b
[4] => c#
[5] => d#
[6] => f
)
I also have an array called $chord_amt:
$chord_amt = array(2,3,4,5,6);
I have used the array_rand function to randomly select one item from the array like so:
$selected_chord_amt = $chord_amt[array_rand($chord_amt)];
Now I want to output whatever number of random chords that this function can produce:
$random_chords = array_rand($scale, $selected_chord_amt);
The problem is, if I print this array, instead of seeing the chord/note values it just shows the keys like this example:
Array ( [0] => 3 [1] => 4 )
How do I get the actual values, so the above output would look like this?
Array ( [0] => b [1] => c# )
Noob question, I know. Sorry.
I'd suggest using a different approach, actually. Using array_rand on this array
$chord_amt = array(2,3,4,5,6);
isn't really needed to generate a random number between 2 and 6. PHP has the rand function for that.
Consider the following instead:
// shuffle the list of chords
shuffle($scale);
// take a slice of it with a random length between 2 and 6
$random_chords = array_slice($scale, 0, rand(2, 6));
Just introduce array_flip with your array_rand:
$random_chords = array_rand(array_flip($scale), $selected_chord_amt);
Prints something like this:
Array
(
[0] => f#
[1] => c#
[2] => d#
)
Like this
$intersect = array_intersect_key($scale, array_flip($random_chords));
Note, I didn't test this, because I'm too lazy to rewrite your arrays, but here's the documentation.
http://php.net/manual/en/function.array-intersect-key.php
http://php.net/manual/en/function.array-flip.php
This is the question as I see it,
How to get a set of items from one array with the keys based on the
values of another array
All random things aside, you have this array
Array
(
[0] => f#
[1] => g#
[2] => a#
[3] => b
[4] => c#
[5] => d#
[6] => f
)
And then you want to get those values based on these keys
Array( 3,4 )
The answer being an array like this
Array('b','c#')
Array(
[User1] => 162
[User2] => 15
[User3] => 158
[User4] => 92
[User5] => 2
[User6] => 3
[User7] => 2
[User8] => 25
[User9] => 10
[User10] => 6
[User11] => 14
)
Above is my array of arrays. This list is completely dynamic - the values(numbers) change, and all of the Users are not numbers, but have actual user names - they don't say User1, they say instead like TomJohnson4512 - on and on, they're all different
All I want to do, is some sort of loop to add up and display/print/echo the values. I don't care about the user names, all I want is a sum of the values.
Any ideas?
All you need to do is use array_sum ( $array ) so assuming your array is called $array, do this
$total = array_sum ( $array );
Let's say I have an array called $array that looks like this once I run asort on it:
Array
(
[1] => Apples
[2] => Bananas
[3] => Cherries
[4] => Donuts
[5] => Eclairs
[6] => Fried_Chicken
)
What is the simplest way to make it so that, after sorting alphabetically, the key that has the value "Donuts" is removed and then put at the end?
I would simply remove the donut element, perform your asort, and then add the donut item back on.
I came up with this. Tested it and confirmed it works. Reordered your array so I could actually see the sorting.
$arr = Array(
1 => "Fried_Chicken",
2 => "Donuts",
3 => "Bananas",
4 => "Apples",
5 => "Eclairs",
6 => "Cherries"
);
// Get donut and key
$donut_key = array_search("Donuts", $arr);
$donut = $arr[$donut_key]; // If you don't need to keep the value, skip this line
// Remove donut
unset($arr[$donut_key]);
// Sort
asort($arr);
// Append Donut
$arr += array($donut_key => $donut);
Array Search
http://php.net/manual/en/function.array-search.php
Key preserving append
http://www.vancelucas.com/blog/php-array_merge-preserving-numeric-keys/
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Combine Two Arrays with numerical keys without overwriting the old keys
OK guys, was searching about this one with no luck - it always points only to array_merge or array_push or array_combine functions which are useless for my purpose.
Here are two arrays (number indexed):
Array (
[0] => 12345
[1] => "asdvsdfsasdfsdf"
[2] => "sdgvsdfgsdfbsdf"
)
Array (
[0] => 25485
[1] => "tyjfhgdfsasdfsdf"
[2] => "mojsbnvgsdfbsdf"
)
and I need to create one "joined" (unioned) array, so it will look like:
Array (
[0] => 12345
[1] => "asdvsdfsasdfsdf"
[2] => "sdgvsdfgsdfbsdf"
[3] => 25485
[4] => "tyjfhgdfsasdfsdf"
[5] => "mojsbnvgsdfbsdf"
)
As I found nothing on this problem I tried by myself ($arr1 and $arr2 are the two small arrays):
$result_array = $arr1;
foreach($arr2 as $v) {
$result_array[] = $v;
}
This is, of course, working fine but I don't like this approach - imagine the situation when there will not be just 3 elements in second array...
Question: is there a better approach or at the best some built-in function (I do not know about)???
array_merge will work without any problem as your using numeric keys ... see the explanation below from the docs
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
emphasis mine
Array merge works fine for your numerically indexed arrays:
<?php
$arrayOne = array(
0 => 12345
,1 => "asdvsdfsasdfsdf"
,2 => "sdgvsdfgsdfbsdf"
);
$arrayTwo = array(
0 => 25485
,1 => "tyjfhgdfsasdfsdf"
,2 => "mojsbnvgsdfbsdf"
);
$arrayMerged = array_merge($arrayOne, $arrayTwo);
print_r($arrayMerged);
?>
output:
Array
(
[0] => 12345
[1] => asdvsdfsasdfsdf
[2] => sdgvsdfgsdfbsdf
[3] => 25485
[4] => tyjfhgdfsasdfsdf
[5] => mojsbnvgsdfbsdf
)