php - How to update one element of an array according to a condition on another element? -
i have array of associative arrays names (this 1 of keys of assoc array) given below:
{'red', 'blue', 'green'}
have larger array names 1 of keys. like
{'id'=>'23fe54','names'=>'red','value'=>'3'},{'id'=>'90ks21','names'=>'red','value'=>'4'},{'id'=>'44cb12','names'=>'blue','value'=>'1'};
according want update smaller (the first one) array.
names key of larger array tells assoc array of smaller array needs updated.
want add value 1 of fields of smaller array.
question how select shorter array using condition: whether these 2 fields match. how make sure 1 gets updated?
edit: expected output:
{'names'=>'red', 'value'=>'7'},{'names'=>'blue','value'=>'1'};
i :
<?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 result array $results = array(); foreach($names $name) { $results[$name] = array('names' => $name, 'value' => 0); } // compute values foreach($values $value) { $results[$value['names']]['value'] += $value['value']; } // keep values $results = array_values($results); // print "jsonified" result echo(json_encode($results)); ?>
Comments
Post a Comment