Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, convert JSON array to Array and only get one object from the Array

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Vinelab\Http\Client as HttpClient;
use App\Requests\SearchRequest;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class SearchResults extends Controller
{
    public function index()
    {
        return view('results.search-results');
    }

    public function store(Requests\SearchRequest $request)
    {

        $search_phrase = $request->input('search');

        $client = new HttpClient;

        $response = $client->get('https://www.reddit.com/search.json?q='. $search_phrase .'');

        $responseArray = $response->json();

        dd($responseArray);

        return view('results.search-results');

    }
}  

Using the above code, I make a call to the reddit API using this HTTP service

https://github.com/Vinelab/http/tree/master

The response that comes back gives me an Array of a lot of data, but I only want to get the title field from this and Parse it into a Laravel array that can be sent to a view where I will display the titles in a foreach loop.

I thought to maybe store the title of the results in the DB and then query the DB and send that through to the view. I am new to all of this so any assistance and theory will be appreciated.

Is there a way in Laravel 5.2 to convert the output of this JSON array to a usable array that can be compact and sent to the view?

like image 816
Devin Gray Avatar asked Feb 24 '16 08:02

Devin Gray


1 Answers

You can do this, to convert json into Array format.

json_decode($response->content(), true);

and can access via this

$response[0]['title']

like image 64
Qazi Avatar answered Sep 16 '22 16:09

Qazi