php Laravel,将JSON数组转换为Array,并且只从Array中获取一个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35597454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel, convert JSON array to Array and only get one object from the Array
提问by Devin Gray
<?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
使用上面的代码,我使用这个 HTTP 服务调用 reddit API
https://github.com/Vinelab/http/tree/master
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.
返回的响应给了我一个包含大量数据的数组,但我只想从中获取标题字段并将其解析为 Laravel 数组,该数组可以发送到我将在 foreach 循环中显示标题的视图.
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?
Laravel 5.2 中有没有办法将这个 JSON 数组的输出转换为一个可以压缩并发送到视图的可用数组?
回答by Qazi
You can do this, to convert json into Array format.
您可以这样做,将 json 转换为数组格式。
json_decode($response->content(), true);
json_decode($response->content(), true);
and can access via this
并且可以通过这个访问
$response[0]['title']
$response[0]['title']