以下是我的JSON数据。
[
{
"id": 1,
"Name": {
"FirstName": "Wilmer",
"LastName": "Crona",
"FullName": "Mr. Cameron Prosacco"
},
"Address": {
"Address1": "84154 Vickie Burg Apt. 994",
"Address2": "Suite 339",
"ZipCode": "89080-0376"
},
"Phone": "316-269-7694 x1364"
},
{
"id": 2,
"Name": {
"FirstName": "Mercedes",
"LastName": "Kshlerin",
"FullName": "Dr. Kellie Bashirian"
},
"Address": {
"Address1": "12638 Cali Spurs",
"Address2": "Suite 353",
"ZipCode": "76622"
},
"Phone": "319-329-3169 x8848"
}
]
在这里,我想要这样的JSON:https://github.com/Zlob/php-json-server,但在方法中。 JSON文件必须是一个文件,并且只能处理一个JSON (db.json).
如果我的JSON文件json1.json , json2.json, etc.
应该怎么做?
答案 0 :(得分:0)
您不能仅解码第一个元素,就可以解码全部并仅获取第一个元素,here is online compiler
<?php
$json = '[
{
"id": 1,
"Name": {
"FirstName": "Wilmer",
"LastName": "Crona",
"FullName": "Mr. Cameron Prosacco"
},
"Address": {
"Address1": "84154 Vickie Burg Apt. 994",
"Address2": "Suite 339",
"ZipCode": "89080-0376"
},
"Phone": "316-269-7694 x1364"
},
{
"id": 2,
"Name": {
"FirstName": "Mercedes",
"LastName": "Kshlerin",
"FullName": "Dr. Kellie Bashirian"
},
"Address": {
"Address1": "12638 Cali Spurs",
"Address2": "Suite 353",
"ZipCode": "76622"
},
"Phone": "319-329-3169 x8848"
}
]';
$data = json_decode($json);
$firstObject = $data[0];
var_dump($firstObject);
答案 1 :(得分:0)
在url中传递数据库名称,并在config中设置数据库名称。将所有json文件放入db文件夹。
namespace App\Http\Controllers;
use Request;
use Response;
use Config;
use JsonServer\JsonServer;
class JsonServerController extends Controller
{
public function handleRequest($db, $uri)
{
$data = Request::all();
$method = Request::method();
$pathToJson = storage_path($db .'.json'); //if your path in inside storage folder of laravel
Config::set('pathToDb', $pathToJson); //here we set db
$jsonServer = new JsonServer();
$response = $jsonServer->handleRequest($method, $uri, $data);
$response->send();
}
}
现在在路线中定义
Route::any('api/{db}/{all}', "JsonServerController@handleRequest")->where('all', '.*');
现在,对于json1数据库的请求将是这样
GET api/json1/posts
POST api/json1/posts
PUT api/json1/posts/1
PATCH api/json1/posts/1
DELETE api/json1/posts/1
对于json2数据库
GET api/json2/posts
POST api/json2/posts
PUT api/json2/posts/1
PATCH api/json2/posts/1
DELETE api/json2/posts/1