php - 如何在 php,laravel 中的不同代码块中使变量值可变
问题描述
任务是从 api 获取 json 用户数据并将其存储在数组中。然后能够对其进行不同的路线更改。
这是来自 api 的数据示例,它们总共有 10 个,并且在一个数组中。
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
我使用这个获取数据:
$jsonurl = "http://jsonplaceholder.typicode.com/users";
$json = file_get_contents($jsonurl);
global $userData;
$userData = json_decode($json);
我用这个在 /users 路由中显示了数据
Route::get('/users', function(){
global $userData;
echo json_encode($userData);
});
我被告知要设置一个 /delete 路由,从数组中删除最后一个对象。
Route::get('/delete', function(){
global $userData;
$lastObjIndex = count($userData) -1;
array_splice($userData, $lastObjIndex,1);
//print_r('last user deleted');
echo json_encode($userData);
$userData = $userData;
});
问题是删除路由不仅工作一次(它不会删除后续的最后一个对象并在再次访问该路由时返回相同的内容)并且在我访问用户路由时没有显示任何更改。数据不存储在服务器中。
我觉得有一些我不知道的东西可以帮助解决这个问题。任何建议将不胜感激。
解决方案
推荐阅读
- javascript - React Infinite Scroll - Intersection Observer API 总是跳回顶部
- python - Boost.python 空指针函数
- xcode - 升级到 Cordova ios6 会导致项目的 xcode 出现错误
- javascript - 如何使用 vanilla JavaScript 选择下拉选项?
- python - Multiprocess.Process 未在空队列上退出
- sql-server - 转换多列
- r - 如何在spring mvc应用程序中运行R
- kubernetes - 基本 Helm 依赖说明
- ruby-on-rails - Rails webpacker:卸载?
- javascript - 如何使用 puppeteer 在页面上注入查找元素