首页 > 解决方案 > 如何在 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;

});

问题是删除路由不仅工作一次(它不会删除后续的最后一个对象并在再次访问该路由时返回相同的内容)并且在我访问用户路由时没有显示任何更改。数据不存储在服务器中。

我觉得有一些我不知道的东西可以帮助解决这个问题。任何建议将不胜感激。

标签: phpnode.jslaravelpersistence

解决方案


推荐阅读