简体   繁体   English

如何根据另一个元素的条件更新数组的一个元素?

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

I have an array of associative arrays whose names (this is one of the keys of the assoc array) are given below: 我有一个关联数组的数组,其names (这是assoc数组的键之一)如下所示:
{'Red', 'Blue', 'Green'}
Now I have another larger array with names as one of the keys. 现在,我有了另一个更大的数组,其中names作为键之一。 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. 较大数组的names键告诉我们较小数组的哪个assoc数组需要更新。
I want to then add the value to one of the fields of the smaller array. 然后,我想将value添加到较小数组的字段之一。

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'}; {'names'=>'Red','value'=>'7'},{'names'=>'Blue','value'=>'1'};

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM