php - Sort array connected to other array

I have to array 1 for age label and 1 for age count. I wanted to sort the label how to make to values array sorted connected to the first one
AgeLabel = ['43 yo', '12 yo', '33 yo', '25 yo']
AgeCount = [ 10, 20 ,30 ,40 ]
expected result
AgeLabel = ['12 yo', '25 yo', '33 yo', '43 yo']
AgeCount = [ 20, 40 ,30 ,10 ]
Answer
Solution:
Many options. For example:
asort($AgeLabel);
$AgeCount = array_map(function ($index) use ($AgeCount) {
return $AgeCount[$index];
}, array_keys($AgeLabel));
$AgeLabel = array_values($AgeLabel); // only if you need ordered keys
or
$combined = array_combine($AgeLabel, $AgeCount);
ksort($combined);
$AgeLabel = array_keys($combined);
$AgeCount = array_values($combined);
Answer
Solution:
The array_multisort function is ideally suited for such tasks. Delivers exactly the expected result.
$AgeLabel = ['43 yo', '12 yo', '33 yo', '25 yo'];
$AgeCount = [ 10, 20 ,30 ,40];
array_multisort($AgeLabel,SORT_ASC,$AgeCount);
Answer
Solution:
Quick and dirty, but i think you get idea. First, merge both arrays, then order by value, and then split them.
$AgeLabel = ['43 yo', '12 yo', '33 yo', '25 yo'];
$AgeCount = [10, 20, 30, 40];
$AgeTmp = [];
foreach ($AgeLabel as $k => $v) {
$AgeTmp[$AgeCount[$k]] = $AgeLabel[$k];
}
asort($AgeTmp);
$AgeLabel = [];
$AgeCount = [];
foreach ($AgeTmp as $k => $v) {
$AgeLabel[] = $k;
$AgeCount[] = $v;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: use the option --with-all-dependencies (-w) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.