【问题标题】:How can I multiply all item in an array with laravel?如何将数组中的所有项目与 laravel 相乘?
【发布时间】:2018-12-17 21:45:25
【问题描述】:

我在控制器中有这样的输出数组

{
  "usia": 0.01761252446184,
  "wife_education": 0.078277886497065,
  "husband_education": 0.0058708414872798,
  "number_of_children": 0.17025440313112,
  "wife_religion": 0.86497064579256,
  "wife_now_working": 0.078277886497065,
  "husband_occupation": 0.23874755381605,
  "living_index": 0.078277886497065,
  "media_exposure": 0.048923679060665
 }

我想将数组的每个元素相乘,例如这样

(美国 * 妻子教育 * 丈夫教育 * 孩子人数 * 妻子宗教 * 妻子现在工作 * 丈夫职业 * 生活指数 * 媒体曝光)

【问题讨论】:

  • 循环遍历数组并乘以每个元素。
  • 你能给我举个例子吗?
  • 我已经在下面回答了
  • 感谢您的帮助

标签: php json laravel naivebayes jsondecoder


【解决方案1】:

将您的数据放入字符串并在 JSON 中解码:

$data = '{  
    "usia": 0.01761252446184,  
    "wife_education": 0.078277886497065,  
    "husband_education": 0.0058708414872798,  
    "number_of_children": 0.17025440313112,  
    "wife_religion": 0.86497064579256,  
    "wife_now_working": 0.078277886497065,  
    "husband_occupation": 0.23874755381605,  
    "living_index": 0.078277886497065,  
    "media_exposure": 0.048923679060665  
}';


$data = json_decode($data, true);

然后循环通过$data进行乘法:

$product = 1;
foreach ($data as $key => $value) {
    $product *= $value;
}

【讨论】:

  • 这非常适合我尝试做的事情,谢谢
【解决方案2】:

PHP foreach:http://php.net/manual/en/control-structures.foreach.php

$items = [];

foreach ($items as $item) {
    // do calculation here
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    相关资源
    最近更新 更多