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条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化