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 (有偿)在ANSYS中 .anf文件
  • ¥45 关于#芯片#的问题:组合逻辑电路设计
  • ¥15 基与机器学习和时间序列分析预测养老服务需求趋势
  • ¥100 求连续两帧图像在水平和垂直上偏移
  • ¥15 mysql全文索引查找指定必须关键词word无效
  • ¥15 Verilog hdl密码锁设计
  • ¥35 基于python的有ssl加密传输的socket聊天室
  • ¥15 数码管亮度控制器设计
  • ¥15 kafka客户端跨网段访问,看日志提示连接的还剩内网地址,且访问不通
  • ¥15 关于c语言代码的问题