Laravel,将JSON数组转换为Array并仅从Array中获取一个对象 [英] Laravel, convert JSON array to Array and only get one object from the Array

查看:1094
本文介绍了Laravel,将JSON数组转换为Array并仅从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');

    }
}  

使用上面的代码,我使用此HTTP服务调用reddit API

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

返回的响应给了我很多数据的数组,但是我只想从中获取title字段并将其解析为Laravel数组,该数组可以发送到视图中,以在其中显示标题一个foreach循环.

我认为也许将结果的标题存储在数据库中,然后查询数据库并将其发送到视图.我不熟悉这一切,因此不胜感激.

Laravel 5.2中是否有一种方法可以将此JSON数组的输出转换为可以压缩并发送到视图的可用数组?

解决方案

您可以执行此操作,以将json转换为数组格式.

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

并且可以通过此访问

$response[0]['title']

<?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?

解决方案

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

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

and can access via this

$response[0]['title']

这篇关于Laravel,将JSON数组转换为Array并仅从Array中获取一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆