doubei2340 2015-06-12 21:15
浏览 114
已采纳

如何在PHP中的foreach循环中返回一个数组[重复]

This question already has an answer here:

I would like to do certain calculation in a function that takes a constant value against different values. To do that I created an array and a variable and also a loop that will take each member of the array and the constant value and pass them to the function that does the calculation. I would like to get an array and then I can do more calculations subsequently.

function subtract($a, $b){
    $c=$b-$a;
    return $c. ',';
    }
    $r=3;
$numbers = array(12, 11, 6, 9);

foreach ($numbers as $index=>$value) {
    $deductions=array(subtract($r, $value));
    //$minimum=min($deductions);
    if (is_array($deductions)){
    //echo $deductions;
    }else{
        //echo "not array";
    }
}
//$minimum=min($deductions);
//echo $minimum;
echo $deductions;

I get "Array" and not 9,8,3,6 Why is this? Any help is greatly appreciated. echo was partial problem, I get Array ( [0] => 6, ) not 9,8,3,6 as I expected?

</div>
  • 写回答

3条回答 默认 最新

  • dongqiu3709 2015-06-12 21:17
    关注

    You cannot echo an array. Try using print_r($deductions) or var_dump($deductions).

    Also, the following line is likely incorrect:

    $deductions=array(subtract($r, $value));
    

    This line will keep replacing the previous $deductions variable so you only end up with one value in your array (6) because 9-3 is 6. If you are wanting to create an array of values you need to add the new value to the array as follows:

    $deductions[] = subtract($r, $value);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP