大家好,
我希望我的帖子有意义,你不会认为我是新手(我有时也会这样做)。
我正在尝试了解将数据发送到laravel 5中的视图并访问这些数据的最佳方式。
我实际上可以做到,但我觉得这样做是错误的。
这是我的控制器:
public function timeline()
{
$array_articles = array();
$sharedcontents = DB::table('follow')->select(DB::raw('GROUP_CONCAT(sharedcontent_id) as concat_article_id'))
->join('sharedcontent_user', 'sharedcontent_user.user_id', '=', 'follow.user_id')
->where('follower_user_id', Auth::user()->id)
->groupBy('sharedcontent_user.sharedcontent_id')
->get();
foreach ($sharedcontents as $sharedcontent) {
$article_ids = $sharedcontent->concat_article_id;
$shareNumber = DB::table('sharedcontent_user')->where('sharedcontent_id', $article_ids)->count();
$row['share_number'] = $shareNumber;
$articles = DB::table('shared_content')
->select( 'sharedcontent_user.sharedcontent_id as sharedId',
'shared_content.id as articleId',
'shared_content.title as articleTitle',
'shared_content.source as articleSource',
'shared_content.image as articleImage'
)
->join('sharedcontent_user', 'sharedcontent_user.sharedcontent_id', '=', 'shared_content.id')
->join('users', 'users.id', '=', 'sharedcontent_user.user_id')
->get();
foreach ($articles as $article){
$shared_content_id = $article->articleId;
$row['title'] = $article->articleTitle;
$row['source'] = $article->articleSource;
$row['image'] = $article->articleImage;
}
array_push($array_articles, $row);
}
$articles = json_encode($array_articles);
return view('timeline', compact('articles'));
}
正如您在开头所看到的,我创建了一个名为:$ array_articles的数组 然后我把我的行放进去。
在将其发送到我的视图之前,我使用JSON对其进行编码,在我看来,我执行了JSON解码。
我的观点:
<div id="timeline-container" class="container">
<?php $articles = json_decode($articles); ?>
@foreach ($articles as $article)
<div id="article-shared-box">
<div class="article-shared-box-left pull-left">
<div class="blend-layer">
<div class="article-shared-picture"><img src="{{ url($article->image) }}" /></div>
<div class="category-square">{{ $article->category }}</div>
<div class="article-shared-title">{{ $article->title }}</div>
<div class="article-shared-source">{{ $article->source }}</div>
</div>
...
如果我不执行此JSON编码和解码,则无法访问我的数据。
我做得对吗?
@Update
如果我不使用JSON进行编码和解码,我总是得到:尝试访问非对象的属性,无论我如何将其传递给视图,无论我如何调用我的数组。
这是我的$ article_array的print_r:
Array ( [0] => Array ( [share_number] => 1 [category] => Startup [sharing_user_id0] => 68 [sharing_user_name0] => 건우 박 [sharing_user_picture0] => https://graph.facebook.com/v2.4/723882664388388/picture?type=normal [comment_number] => 1 [most_recent_comment] => hhhh [comment_author] => 건우 박 [title] => 전북도 내 스타트업 육성 … 300억 규모 창조경제 혁신펀드 본격 운용 [source] => Platum [image] => http://platum.kr/wp-content/uploads/2015/07/11941_800799769932697_1056826482061661861_n.jpg ) [1] => Array ( [share_number] => 1 [category] => Startup [sharing_user_id0] => 68
答案 0 :(得分:1)
您不需要编码和解码,因为这只是浪费时间。您可以将PHP变量提供给您的视图,不需要任何编码:
return view('timeline', array('articles' => (object) $array_articles));