2014-09-20 139 views
0

我有一个函数,它从数据库中获取值并返回。当我回应时,该值确实存在。但返回值为空;函数返回NULL :: laravel

public static function getCountryCode($country) {  
    $country = (int) $country;  
    $x = Country::where('id', $country)->get(); 
    $country_code = '';   
    foreach($x as $row)    
     $country_code = $row->alpha_2; 
    //return 'bd';  
    echo $country_code;   
    return $country_code; 
} 

不知道那里有什么问题。这是一个laravel项目。正在调用该方法

public function countryselect() 
{ 
    $country_id = HomeController::detectCountry(); 
    $country_code = SiteController::getCountryCode($country_id); 
    var_dump($country_code); 
    return View::make('Layout.countryselect', compact('country_id', 'country_code')); 
} 
+0

你可以显示调用这个方法的代码吗? – bcmcfc 2014-09-20 07:38:11

+0

'public function countryselect() \t { \t \t $ country_id = HomeController :: detectCountry(); \t \t $ country_code = SiteController :: getCountryCode($ country_id); \t \t var_dump($ country_code); \t \t return View:make('Layout.countryselect',compact('country_id','country_code')); \t}' – 2014-09-20 07:42:27

+0

如果将其添加到问题中,格式化会更容易。有一个待处理的编辑,但需要引入。 – bcmcfc 2014-09-20 07:44:42

回答

1

你不必用“的foreach”功能

功能。你可以用更简单的方式获得国家代码。只需在getCountryCode()中进行一些更改,如

public static function getCountryCode($countryId) { 
    $countryId = (int) $countryId;  
    $country = Country::where('id', $countryId)->get()->first(); 
    return $country->code; 
} 

这将返回指定国家/地区ID的国家/地区代码。使用变量的描述性名称,就像你用于函数

+0

thnx让我知道这个功能 – 2014-09-21 07:47:57

+0

你的问题是用这个解决的吗? – user4055288 2014-09-21 09:20:03