我如何使变量值在php,laravel中的不同代码块中可变

问题描述 投票:1回答:1

该任务是从api获取json用户数据并将其存储在数组中。然后可以更改它的不同路线。

这里是来自api的数据示例,它们总共10个,并在一个数组中。

  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "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": "[email protected]",
    "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;

});

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

我觉得我不知道有什么可以帮上忙。任何建议将不胜感激。

php node.js laravel persistence
1个回答
0
投票

如果要删除数组中的最后一项,则可以使用类似这样的内容

global $userData;
$lastElement = last($userData);
unset($lastElement);

我希望这对您有用

© www.soinside.com 2019 - 2024. All rights reserved.