2017-12-21 25 views
1

postgres 데이터베이스가 있고 두 개의 열 ('id'는 기본 키, 'data'는 제목이있는 JSONB 데이터 세트를 저장하는 테이블을 가지고 있습니다. 콘텐츠 등).Laravel Blade를 사용하여 Postgres에서 JSON 데이터 표시

현재 전체 테이블 또는 각 '데이터'만 표시 할 수 있지만 '데이터'에서 개별 데이터 (예 : 제목)를 가져올 수 없습니다.

Route::get('/home', function() { 
    $articles = DB::table('articles')->get(); 
    $results = json_decode($articles, true); 
    return view('home', compact('articles', 'results')); 
}); 

home.blade.php 템플릿 : 여기

는 나뿐만 아니라 JSON 디코딩으로, JSON으로 데이터를 끌어 시도했다 경로입니다. 나는 기사와 결과를 사용하여 제목을 표시하려했습니다. 내가 할 수있는 최선은 전체 테이블을 표시하고,하지만 난 제목 호출 할 수 없었다 :

@foreach ($results as $result)    
    <div>{{ $result->title }}</div> 
@endforeach 

@foreach ($articles as $article)    
    <div>{{ $article->title }}</div> 
@endforeach 

@foreach ($results as $result)    
    <div>{{$result['data']}}</div> //this shows the whole json object, posted below 
@endforeach 

@foreach ($results as $result)    
    <div>{{$result['data']['title']}}</div> //I believe this should work, but I get Illegal String Offset 'title' as an error, 
@endforeach 

내가 입수 한 오류 중 일부 : 여기

htmlspecialchars() expects parameter 1 to be string, array given 
Array to string conversion 
Illegal string offset 'title' 
Something about calling something that's not there 

것은 무엇 JSON의 목적은 같다 json_decode 후 ($ 결과 [ '데이터'] 위) :

{"url": "http://omgili.com/ri/.wHSUbtEfZQrTHDoKYSJbjrpQN.N5MJgWJskXd50cUpWKooC_zdZBj5IfjtQ82V5YE9KjMI9MkoEoWsmLqcSDiWUKMSrDShx9H3vPUjRQuW0sylmueXyZg--", "text": "Cable companies are ove....", "uuid": "8c43aa206860570df0a86ff11f619235dea6e2bf", "title": "Cable companies are looking for ways to limit password sharing", "author": "theverge.com", "rating": null, "thread": {"url": "http://omgili.com/ri/.wHSUbtEfZQrTHDoKYSJbjrpQN.N5MJgWJskXd50cUpWKooC_zdZBj5IfjtQ82V5YE9KjMI9MkoEoWsmLqcSDiWUKMSrDShx9H3vPUjRQuW0sylmueXyZg--", "site": "theverge.com", "uuid": "8c43aa206860570df0a86ff11f619235dea6e2bf", "title": "Cable companies are looking for ways to limit password sharing", "social": {"vk": {"shares": 0}, "gplus": {"shares": 0}, "facebook": {"likes": 0, "shares": 0, "comments": 0}, "linkedin": {"shares": 0}, "pinterest": {"shares": 0}, "stumbledupon": {"shares": 0}}, "country": "US", "published": "2017-12-20T18:17:00.000+02:00", "site_full": "www.theverge.com", "site_type": "news", "main_image": "https://cdn.vox-cdn.com/thumbor/wCruRyorIkyClceG2T4Q0BsYk7Y=/0x73:1020x607/fit-in/1200x630/cdn.vox-cdn.com/assets/4562901/theverge1_1020.jpg", "spam_score": 0, "title_full": "Cable companies are looking for ways to limit password sharing - The Verge", "domain_rank": 496, "site_section": "http://www.theverge.com/tech/rss/index.xml", "replies_count": 0, "section_title": "The Verge - Tech Posts", "site_categories": ["media"], "performance_score": 0, "participants_count": 1}, "crawled": "2017-12-20T18:29:59.008+02:00", "entities": {"persons": [{"name": "rutledge", "sentiment": "none"}, {"name": "tom rutledge", "sentiment": "none"}], "locations": [], "organizations": [{"name": "netflix", "sentiment": "none"}, {"name": "bloomberg", "sentiment": "none"}, {"name": "viacom", "sentiment": "none"}, {"name": "ubs", "sentiment": "none"}, {"name": "espn", "sentiment": "none"}]}, "language": "english", "published": "2017-12-20T18:17:00.000+02:00", "highlightText": "", "ord_in_thread": 0, "external_links": [], "highlightTitle": ""} 

답변

2

당신은 JSON의 Collection 객체 대신, 포스트 그레스에서 설득력 반환을 데이터를 쿼리 할 때 코드에 문제가있다 끈. 따라서 라인 :

$results = json_decode($articles, true); 

결코 작동하지 않습니다. json_decode 함수는 문자열 (UTF8 인코딩 된 문자열)과 만 작동합니다.

실제로 나타나는 오류는 $article->data이 실제로 구문 분석되지 않고 문자열로 남아 있기 때문입니다.

Array to string conversionIllegal string offset 문자열을 배열로 처리 할 때 오류가 발생합니다.

기본적으로 JSON 데이터를 올바르게 구문 분석/해석하려면 컬렉션을 거쳐 수동으로 변환해야합니다. Eloquent\Collection::map 함수를 사용하여 데이터를 연관 배열에 올바르게 매핑 할 수 있습니다.

$results = $articles->map(function($article){ 
    return [ 
     'id' => $article->id, 
     'data' => json_decode($article->data, true) 
    ]; 
}) 
+0

철저한 설명 및 답변 감사합니다. – Alteredorange