【问题标题】:Laravel, convert JSON array to Array and only get one object from the ArrayLaravel,将 JSON 数组转换为数组,只从数组中获取一个对象
【发布时间】:2016-06-06 11:10:23
【问题描述】:
<?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

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

我想可能将结果的标题存储在数据库中,然后查询数据库并将其发送到视图。我对所有这些都是新手,因此我们将不胜感激任何帮助和理论。

在 Laravel 5.2 中有没有办法将这个 JSON 数组的输出转换为可以压缩并发送到视图的可用数组?

【问题讨论】:

    标签: php arrays json laravel-5.2


    【解决方案1】:

    您可以这样做,将 json 转换为 Array 格式。

    json_decode($response-&gt;content(), true);

    并且可以通过这个访问

    $response[0]['title']

    【讨论】:

    • 我理解这里的逻辑,但我得到了这个异常 Call to undefined method Vinelab\Http\Response::first()
    • 如果我删除第一个它会引发对未定义方法 Vinelab\Http\Response::toArray() 的调用,这直接来自使用 $client 变量进行 HTTP 调用
    • 我明白了,你正在使用API​​,试试这个$response[0]['title']
    • 不能使用 Vinelab\Http\Response 类型的对象,因为数组是响应,这适用于 JSON 数组吗?我将数组作为 JSON,但现在只想将其转换为普通数组,我可以用 eloquent 将其保存在数据库中
    • 试试这个,我相信这会将你的 JSON 转换为普通数组,json_decode($response-&gt;json(), true);
    猜你喜欢
    • 1970-01-01
    • 2016-09-19
    • 2014-12-24
    • 2022-07-06
    • 2017-08-11
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多