【问题标题】:Sum values ​in an array对数组中的值求和
【发布时间】:2022-07-20 06:54:29
【问题描述】:

我的代码 sn-p:

    $price = row_select('keyword_type_price', ['keyword_type_id' => $keyword['keyword_type'], 'word' => $keyword['word']], ['price'])['price'];    
        $array = [$price];
        printR($array); 
}

结果:

数组 ( [0] => 30000 ) 大批 ( [0] => 55000 ) 大批 ( [0] => ) 大批 ( [0] => ) 大批 ( [0] => 40000 ) 大批 ( [0] => ) 大批 ( [0] => ) 大批 ( [0] => ) 大批 ( [0] => ) 大批 ( [0] => ) 大批 ( [0] => ) 大批 ( [0] => ) 大批 ( [0] => 40000 ) 大批 ( [0] => 40000 ) 大批 ( [0] => 40000 ) 大批 ( [0] => 40000 ) 大批 ( [0] => 40000 ) 大批 ( [0] => 40000 ) 大批 ( [0] => 40000 ) 大批 ( [0] => 40000 ) 大批 ( [0] => 40000 ) 大批 ( [0] => 40000 ) 大批 ( [0] => 40000 )

问题是我如何将它们合并到一个数组中,以便能够使用 array_sum 函数对数组中的值求和,或者是否有另一种更优化的方式我愿意吸收。

【问题讨论】:

  • 改用$array[] = $price;使用您的声明 $array = [$price],您将在每次迭代时启动一个新数组。

标签: php codeigniter


【解决方案1】:

在循环之前初始化数组

$array = [];

然后

$array = [$price]; 更改为$array[] = $price;

给它一个比数组更好的名字也是一个好主意。

摘自:https://medium.com/swlh/how-to-better-name-your-functions-and-variables-e962a4ef335b

在命名函数、变量或类时,应牢记以下几点:

Choose a word with meaning (provide some context)
Avoid generic names (like tmp)
Attach additional information to a name (use suffix or prefix)
Don’t make your names too long or too short
Use consistent formatting

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    相关资源
    最近更新 更多