0

How can I turn:

$array1 = array(34=>"key1",54=>"key3",12=>"key2");

$array2 = array(44=>"key4",12=>"key2",1=>"key1");

into:

$array = ("key3"=>54,"key4"=>44,"key1"=>35,"key2"=>24);

How to add the value of the keys and sort by value?

Rasclatt
  • 12,249
  • 3
  • 21
  • 32
Yanks
  • 161
  • 2
  • 15
  • plz some body help me – Yanks Aug 09 '15 at 07:45
  • Downvoting because you've shown no evidence of effort or research. Begging impatiently after 15 minutes doesn't make me any more well-disposed to help you, adding information about where exactly you're stuck would. – IMSoP Aug 09 '15 at 08:10
  • Is the reversed order of keys and values in the input intentional? In that case, is there a reason to why you can't just reverse it in the declaration? – Anders Aug 09 '15 at 08:11

3 Answers3

1

You could flip the arrays, merge and sum matching key values, followed by a reverse sort:

$a1 = array(34=>"key1",54=>"key3",12=>"key2");
$a2 = array(44=>"key4",12=>"key2",1=>"key1");

function addRev($a1,$a2) {

    $a1 = array_flip($a1);
    $a2 = array_flip($a2);

    $added = array();
    foreach (array_keys($a1 + $a2) as $key) {
        $added[$key] = @($a1[$key] + $a2[$key]);
    }

    arsort($added);
    return $added;
}

print_r(addRev($a1, $a2));

Result:

Array
(
    [key3] => 54
    [key4] => 44
    [key1] => 35
    [key2] => 24
)
l'L'l
  • 40,316
  • 6
  • 77
  • 124
0

You can use array_merge() function for "adding" arrays. http://php.net/manual/en/function.array-merge.php

For sorting, you can check this link: Sorting an associative array in PHP

Community
  • 1
  • 1
Alim Giray Aytar
  • 706
  • 8
  • 14
  • OP does not just want to merge arrays, but add entries with the same key. Also, your PHP documentation link is not to the english documentation. – Anders Aug 09 '15 at 08:09
0

try this, I add explanations in comments

$array1 = array(34=>"key1",54=>"key3",12=>"key2");
$array2 = array(44=>"key4",12=>"key2",1=>"key1");


// fliping arrays

$a1r = array_flip($array1);
$a2r = array_flip($array2);

var_dump($a1r);
var_dump($a2r);


// adding the 2 arrays, final result in $a1r

foreach ($a2r as $key => $value) {
    if (!isset($a1r[$key])) {
        $a1r[$key] = 0;
    }

    $a1r[$key] += $value;
}

var_dump($a1r);
mmm
  • 1,012
  • 1
  • 7
  • 15