duanla4959 2014-08-09 15:20
浏览 42
已采纳

为什么我的函数不返回字符串?

I have a function that first looks for premium brands to add to a string. If there is not enough premium brands, it continues and ads non-premium brands (max 4 brands).

I'm able to echo the string inside the function and it shows 4 brands, but I'm not able to return the string. Why is that?

$bnames = addBrandNameToTitle($model);
echo $bnames; // This is empty

function addBrandNameToTitle($model, $brandNames = array(), $ispremium = true){
    if($ispremium):
        foreach ($model->brands as $brand):
            if ($brand->isPremium() && count($brandNames)  < 4):
                array_push($brandNames, $brand->name);
            endif;

            if(count($brandNames)  >= 4){
                return implode(',', $brandNames);
            }
        endforeach;
        // If not enough premium, add non-premium brands
        addBrandNameToTitle($model, $brandNames, false);
    else:
        foreach ($model->brands as $brand):
            if (!$brand->isPremium() && count($brandNames) < 4):
                array_push($brandNames, $brand->name);
            endif;
        endforeach;
        $bnames = implode(',', $brandNames);
        echo $bnames; // <-- This lists 4 brands
        return $bnames; // <-- But this is not returning the string. Why?
    endif;
}
  • 写回答

1条回答 默认 最新

  • douzong3599 2014-08-09 15:27
    关注

    In this section of code, you forgot to return the value

    // If not enough premium, add non-premium brands
    return addBrandNameToTitle($model, $brandNames, false);  // Add a return
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题