2016-11-07 36 views
0

我在查找數組中的特定關鍵字時遇到問題。我正在使用Laravel。array_search()在第二個參數上拋出錯誤

我想找到具有特定關鍵字的特定帖子,完全像Twitter功能。

當來訪www.foobar.com/shoutouts/$hashtag以下功能被執行:

public function shoutoutSpecific($hashtag) { 
     $hashtag = '#' . $hashtag; 
     $shoutouts = Shoutout::orderBy('created_at', 'DESC')->get(); 

     foreach($shoutouts as $shoutout) { 
      if (array_search($hashtag, $shoutout->hashtag) !== false) { 
      $shoutouts2 = $shoutouts2 . $shoutout; 
      } 
     } 

     return view('shoutout', compact('shoutouts2')); 
    } 

爲shoutout->主題標籤的數據庫表包含例如以下

a:1:{i:0;s:5:"#test";} 

所以當訪問www.foobar.com/shoutouts/test,該函數應該定位具有#test#標籤的特定shoutout,從而將它們投射到可以在視圖中循環播放的數組中。

然而,當我訪問www.foobar.com/shoutouts/test,我得到

array_search() expects parameter 2 to be array, string given 

,我不明白這一點,因爲第二個參數是在數據庫中的數組。

所有幫助表示讚賞。

+0

它告訴你什麼是錯的。你傳遞了一個字符串。 'array_search()'爲一個給定的字符串搜索一個數組的值。 – Jaime

回答

0

a:1:{i:0;s:5:"#test";}是序列化值:

array(1) { 
    [0]=> string(5) "#test" 
} 

所以首先要使用即unserialize($string)函數來反序列化。之後array_search應該按預期工作。

Laravel可以通過定義你希望哪個屬性進行訪問時,被鑄造成JSON自動做到這一點:

protected $casts = [ 
    'hashtag' => 'array' 
]; 

更多,在這裏:https://laravel.com/docs/5.3/eloquent-mutators#array-and-json-casting

相關問題