Home > Enterprise >  Combine value of unique keys in array
Combine value of unique keys in array

Time:07-08

I am a complete newbie at programming and am trying to create a function that combines the values of unique keys and then returns the highest value.

$arr = array(
   "Canada"=>500,
   "US"=>2,
   "Mexico"=>40,
   "Mexico"=>50,
   "US"=>170,
   "Canada"=>25,
   "Mexico"=>5,
   "US"=>300
);

Right now, if I print out the array, I get:

Array ( [Canada] => 25 [US] => 300 [Mexico] => 5 ) 

I want it to print out the following:

Canada = 525

I've tried during foreach loops, array_sum, array_map, array_reduce, but to no avail :(

CodePudding user response:

As arrays always have unique keys I recommend you re-format your input array to an array of arrays like so

$arr = array(
  array("Canada"=>500),
  array("US"=>2),
  array("Mexico"=>40),
  array("Mexico"=>50),
  array("US"=>170),
  array("Canada"=>25),
  array("Mexico"=>5),
  array("US"=>300)
);

You can then parse this array in a loop - adding the values t0 $counter_array

$counter_array = array();
foreach ($arr as $arrays) {
  foreach ($arrays as $key => $value) {
    if (!isset($counter_array[$key])) {
      $counter_array[$key] = 0;
    }
    $counter_array[$key]  = $value;
  }
}

print_r($counter_array);


Array
(
    [Canada] => 525
    [US] => 472
    [Mexico] => 95
)

CodePudding user response:

Array Data Structure require unique identifier for each value. It's due to the way it's stored in memory. Ask yourself: How would program distinguish between the two keys?

In your example. Let's say I'm trying to fetch a value of $arr["Canada"]. You put 2 different values to that identifier (key). Logically, the last one will override the previous one. And that is what exactly will happen if you will try to instantiate this array.

In this case I would change the way of array instantiation to make it something like this:

$arr = [
    "Canada" => [500, 25],
    "US" => [2, 170, 300],
    "Mexico" => [40, 50, 5]
];

$result = array_map(function ($e) {
    return array_sum($e);
}, $arr);

var_export($result);

array ( 'Canada' => 525, 'US' => 472, 'Mexico' => 95)
  • Related