doubianxian6557
doubianxian6557
2013-12-01 16:26

PHP Division功能相当于array_product

已采纳

I'm looking for an equivalent to the PHP function array_product http://php.net/manual/en/function.array-product.php in that sense, that I would like to have a division on two values in an array. How do I do this? (And why doesn't it exist yet?)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doulan9419 doulan9419 8年前

    Do you mean like this? It's quite strange.

    function array_div(array $arr)
    {
        $first = array_shift($arr);
        foreach($arr as $num)
        {
            $first /= $num;
        }
        return $first;
    }
    
    echo array_div([100, 25, 0.5]); //8
    echo array_div([99, 3]); //33
    
    点赞 评论 复制链接分享
  • doushi9376 doushi9376 8年前

    You can use array_reduce():

    $arr = array(100, 25, 0.5);
    $initial = array_shift($arr);
    $res = array_reduce($arr, function($r, $v) { return $v == 0 ? $r : ($r / $v); } , $initial);
    

    Of course add some checks to see if $v is zero.

    点赞 评论 复制链接分享