0

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 ]
2
  • Why don't you try an object array?. like const age = [{label:'43 Y0', count:10}, {label:'12 yo', count:20}, ......] Commented Aug 31, 2021 at 8:59
  • 1
    Show us what you've tried so far, your best attempt (code). Please read How to Ask and take the tour! Commented Aug 31, 2021 at 8:59

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

2

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;
}

3 Comments

For the last part (separating keys and values again) you can use array_keys and array_values, so you don't have to iterate over each one. Those are built-in PHP functions.
correct, stas.yaranovs answer has this and array_combined() and is quicker, so i dont update my answer...but thanks for the hint :)
This solution gives incorrect results if $ AgeCount contains the same values how [10,10,20 ..]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.