2017-09-14 53 views
0

enter image description here验证具有相同的验证功能的PHP laravel所有对象价值

以上为对象的DD()一个的结果,现在我所做的是

//$car is a object variable 
$car->corporate_id = some_function($car->corporate_id); 
$car->corporate_name = some_function($car->corporate_name); 
$car->member_id = some_function($car->member_id); 

而不是做上述方式,我怎么能达到像

$data = some_function($car); 
//it will go through all $car properties and run the same validation 

有人可以告诉我如何实现这一目标?

回答

0

我发现它, 第一的foreach的对象,例如$汽车为对象,

foreach($cars as $car) 
{ 
    $carr = $car->map(function ($item, $key) 
      { 

       //code logic goes here 
       // $key variable is the index key of the object 
       // $item variable is value of the object 
       $data = $item + 1;   
       return $data ; 
      }); 

     //after this you can simply access the object attribute like usual 
     $carr->car_number; 
     $carr->car_name; 


} 

但是这是解决方案是使用laravel Collection,你也可以通过简单调用将数组转换为集合

$collection = collect($anyArray); // make sure to include Illuminate\Support\Collection this class 
            //in order for to use the collection functionality 
1

函数体这样

if(!is_object($car)) return 'function expect a car object'; 

if(isset($car->corporate_id)) 
    $car->corporate_id = some_other_function($car->corporate_id); 

if(isset($car->corporate_name)) 
    $car->corporate_id = some_other_function($car->corporate_name); 
........... 

return $car; 
+0

不,我期待al l对象属性通过调用一个函数来运行相同的验证函数,而不是像这样一个一个地执行 –