duanchuaiwan0063 2014-10-19 21:41
浏览 23
已采纳

如何使用PHP将数组的值除以常量并保持关联键?

I have following array:

Array
(
[ALFA] => 474
[BETA] => 359
[GAMMA] => 248
[DELTA] => 147
[EPSILON] => 137
[ZETA] => 135
)

and would like to divide it by a constant X, for example 213, so in the end I have following array as result:

Array
(
[ALFA] => 2.2253
[BETA] => 1.6854
[GAMMA] => 1.1643
[DELTA] => 0.6901
[EPSILON] => 0.6431
[ZETA] => 0.6338
)

I'm doing this

foreach($array as $v){
    $newArray[] = ($v / $divisor); //in our examploe $divisor = 213.
}    

but then the new array has indexed keys just like that:

Array
(
[0] => 2.2253
[1] => 1.6854
[2] => 1.1643
[3] => 0.6901
[4] => 0.6431
[5] => 0.6338
)

Many thanks in advance!

  • 写回答

2条回答 默认 最新

  • dputlf5431 2014-10-19 21:43
    关注
    array_walk(
        $myArray,
        function(&$value) use ($divisor) {
            $value /= $divisor;
        }
    );
    

    Note that this changes the original array directly

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥18 模拟电路问题解答有偿
  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题