dtsc14683 2017-12-14 00:22
浏览 14
已采纳

PHP - 适合100%的数字数组

I'm working on poll results and I want to fit 4 dynamic numbers in 100%. Sorry if I didn't explain it correctly, I'm native Dutch and I'm having a hard time trying to explain it correctly.

This is what I mean: If my poll results are like this;

  • Answer 1: 1 vote
  • Answer 2: 1 vote
  • Answer 3: 1 vote
  • Answer 4: 1 vote

The result should be 25, 25, 25, 25.

Is there a way to calculate this? I have all answer counts in a array like this:

$all_values = array($answers_1, $answer_2, $answer_3, $answer_4);

How can I accomplish this in PHP?

  • 写回答

1条回答 默认 最新

  • douhuan1950 2017-12-14 00:32
    关注

    Should be easy enough. You can use array_sum and array_map with a custom function:

    $sum = array_sum($all_values);
    $result = array_map(function ($value) use ($sum) {
      return $value * 100 / $sum;
    }, $all_values);
    

    You could cast the results before returning, but I don't know what type you want.

    Short Demo.

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

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)