dongtuoao7987 2014-01-26 15:38
浏览 32
已采纳

PHP - 更新单维数组(通过在键值中添加或减去值)

For an array like:

Array1 ( [a] => 1 [b] => 2 [c] => 7 [d] => )

I would like to update certain values if keys with variable match.

For example, I am have two variables (a=0.5 and c=0.25). I may also have one or more than two variables which would need to be added to the array.

In the case where I have two variables (a=0.5 and c=0.25).

Can one update the array by adding the proper variable to its corresponding key in the array?

End result:

Array1 ( [a] => 1.5 [b] => 2 [c] => 7.25 [d] => )

Can't think of a way to add values to original array (be from single array, multidimensional array or variables where the key match). I am a newbie to adding or updating array's key value, and am super stuck at these right now. Trying all kinds of things. Thank you!

PS. I am not playing around with converting the original array to variables, perform the math, then convert back again to single dimensional array, but it will not do since the array may have unique keys every time... hmmm...

  • 写回答

1条回答 默认 最新

  • dou5454954610 2014-01-26 15:45
    关注

    Basically what you want to do is add the values to the array by referencing a key name of a, b etc. You should just be able to do this:

    $array['a'] += $value_to_add;
    

    ... but you might get undefined index errors if the variable doesn't exist already. So the best way to do it would be to set the key if it doesn't exist already:

    if(!array_key_exists('a', $array))
        $array['a'] = 0;
    
    $array['a'] += $new_value;
    

    Now, if you're talking about having an array like your example:

    Array1 ( [a] => 1 [b] => 2 [c] => 7 [d] => )
    

    ...and these variables:

    $a = 0.5;
    $c = 0.25;
    

    ...and wanting to arbitrarily adding unknown variable names to their respective keys in your array, you'll need to get the variable name as a string so that you can search for it in your array.

    If this is the case, you'd be better off putting the variables to add into an array:

    $vars_to_add = array(
        'a' => 0.5,
        'c' => 0.25
    );
    

    ...then you can do a simple loop over the new array to add them to the original array:

    foreach($vars_to_add as $key => $current) {
        if(!array_key_exists($key, $original_array))
            $original_array[$key] = 0; // initialize blank variable
    
        // add new value to original array
        $original_array[$key] += $current;
    }
    

    End result of $original_array would look like this:

    Array1 ( [a] => 1.5 [b] => 2 [c] => 7.25 [d] => )
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部