How to update one element of an array according to a condition on another element?

125 views Asked by At

I have an array of associative arrays whose names (this is one of the keys of the assoc array) are given below:
{'Red', 'Blue', 'Green'}
Now I have another larger array with names as one of the keys. Like
{'id'=>'23fe54','names'=>'Red','value'=>'3'},{'id'=>'90ks21','names'=>'Red','value'=>'4'},{'id'=>'44cb12','names'=>'Blue','value'=>'1'};

According to this I want to update the smaller (the first one) array.
The names key of the larger array tells us which assoc array of the smaller array needs to be updated.
I want to then add the value to one of the fields of the smaller array.

The question is how do I select the shorter array using the condition: whether these two fields match. How do I make sure only that one gets updated?

EDIT: Expected output:
{'names'=>'Red', 'value'=>'7'},{'names'=>'Blue','value'=>'1'};

1

There are 1 answers

0
Christophe Quintard On

I would do this :

<?php
$names = array('Red', 'Blue', 'Green');
$values = array(
    array('id'=>'23fe54','names'=>'Red','value'=>'3'),
    array('id'=>'90ks21','names'=>'Red','value'=>'4'),
    array('id'=>'44cb12','names'=>'Blue','value'=>'1')
);

// prepare the result array
$results = array();
foreach($names as $name) {
    $results[$name] = array('names' => $name, 'value' => 0);
}

// compute values
foreach($values as $value) {
    $results[$value['names']]['value'] += $value['value'];
}

// keep only values
$results = array_values($results);

// print "jsonified" result
echo(json_encode($results));
?>