2017-11-02 8 views
3

を持つオブジェクトのプロパティ私はこのような変数を持つオブジェクトのプロパティを参照する必要があります。リファレンス変数

$user = User::find(1); 
$mobile = $user->getData('phone.mobile'); 

オブジェクトの$ dataプロパティの値は、JSON配列です。

class User extends Authenticable { 

    protected $fillable = [ 
     'email', 
     'password', 
     'data', 
     'token', 
    ]; 

    protected $casts = [ 
     'data' => 'array', 
    ]; 

    public function getData($key = null){ 
     if($key == null){ 
      // Return the entire data array if no key given 
      return $this->data; 
     } 
     else{ 
      $arr_string = 'data'; 
      $arr_key = explode('.', $key); 
      foreach($arr_key as $i => $index){ 
       $arr_string = $arr_string . "['" . $index . "']"; 
      } 
      if(isset($this->$arr_string)){ 
       return $this->$arr_string; 
      } 
     } 
     return ''; 
    } 
} 

上記のコードは、常に「」を返しますが、データベースに保存されている実際の値は$this->data['phone']['mobile']返します。今のところ、私のユーザークラスは次のようになります。 私は間違った方法でキーを参照していると思います。文字列を指定して、値にアクセスする正しい方法を指し示すことができます。'phone.mobile'

答えて

2

Laravelは実際にあなたのために組み込みのヘルパー関数を持っていますarray_getと呼ばれるんしようとする:

public function getData($key = null) 
    { 
     if ($key === null) { 
      return $this->data; 
     } 
     return array_get($this->data, $key); 
    } 

詳細についてはドキュメントを参照してください:あなたもそれをしない機能で答えを投稿することができればあなたの助けをhttps://laravel.com/docs/5.5/helpers#method-array-get

+0

おかげで、それはいいだろう。私はどのようにそれが完了したかを見たいと思います。 – Tales

関連する問題