Reputation: 731
I have two arrays like this:
Array (key is ID user, value is name) #1
[7] => "John Doe"
[12] => "Steve Jobs"
[20] => "Brad Pitt"
Array (key is ID user, value is score for sorting) #2
[7] => 45
[12] => 27
[20] => 50.5
Expected result after sorting (lowest value first, highest last)
[12] => "Steve Jobs"
[7] => "John Doe"
[20] => "Brad Pitt"
What is easiest way to achiev that? Thanks
Upvotes: 0
Views: 96
Reputation: 106
This works for me:
<?php
$names[7] = "John Doe";
$names[12] = "Steve Jobs";
$names[20] = "Brad Pitt";
$ages[7] = 45;
$ages[12] = 27;
$ages[20] = 50.5;
// Sort second array on age values
asort($ages);
// Loop through sorted age array
foreach($ages as $key => $value) {
// Get name and insert into new array
$sortedArray[$key] = $names[$key];
}
// Print sorted names
print_r($sortedArray);
?>
Upvotes: 0
Reputation: 5203
A simple way of doing what you want is using asort to sort the array and the array_replace_recursive to merge the values. (Example)
<?php
$a = [
7 => "John Doe",
12 => "Steve Jobs",
20 => "Brad Pitt"
];
$b = [
7 => 45,
12 => 27,
20 => 50.5
];
asort($b);
$result = array_replace_recursive($b,$a);
print_r($result);
?>
Upvotes: 2
Reputation: 3222
What I'd recommend you to do is: create array with associative array in it, because that would be way more readable
$people = [
['name' => 'John Doe', 'score' => 45],
['name' => 'Steve Jobs', 'score' => 27],
['name' => 'Brad Pitt', 'score' => 50.5],
]
And sorting with usort() - something like this:
function sortScores($a, $b) {
return ($a['score'] - $b['score']);
}
usort($people, 'sortScores');
This is more like an advice btw
Edit:
for select:
foreach ($people as $p) {
echo $p['name']
}
it's as simple as that, just add tags to your echo or however you are printing that
Upvotes: 0
Reputation: 342
Try this
asort($arr2);
$finalArr=[];
foreach($arr2 as $key => $value){
$finalArr[$key]=$arr1[$key];
}
We are doing sorting and maintaining the index association (asort)
We are looping the sorted array and comparing with the first array and storing to the final array
Upvotes: 2