David Fim
David Fim

Reputation: 33

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 ]

Upvotes: 0

Views: 62

Answers (3)

jspit
jspit

Reputation: 7693

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

Upvotes: 2

stas.yaranov
stas.yaranov

Reputation: 1787

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

Upvotes: 3

bob
bob

Reputation: 625

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

Upvotes: 2

Related Questions