doubei2340 2015-06-12 13:15
浏览 115
已采纳

如何在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 13: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条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 MAX98357a(关键词-播放音频)
  • ¥15 Linux误删文件,请求帮助
  • ¥15 IBMP550小型机使用串口登录操作系统
  • ¥15 关于#python#的问题:现已知七自由度机器人的DH参数,利用DH参数求解机器人的逆运动学解目前使用的PSO算法
  • ¥15 发那科机器人与设备通讯配置
  • ¥15 Linux环境下openssl报错
  • ¥15 我在使用VS编译并执行之后,但是exe程序会报“无法定位程序输入点_kmpc_end_masked于动态链接库exe上“,请问这个问题有什么解决办法吗
  • ¥15 el-select光标位置问题
  • ¥15 单片机 TC277 PWM
  • ¥15 在更新角色衣服索引后,Sprite 并未正确显示更新的效果该如何去解决orz(标签-c#)
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部