删除数组的最后一项

时间:2018-03-27 12:01:02

标签: php mysql arrays

我在数据库中有一个表,我从中获得了一个JSON。

当我解码结果时,我有一个这样的数组:

array("1" => "Jason" ,
      "2" => "Jimmy" ,
      "3" => "Christopher" , 
      "4" => "Bruce" , 
      "5" => "james" , 
      "6" => "Mike" ,
      "7" => "Brad" );

如何在添加新项目时从数据库中删除最后一项。

例如:

当我添加WalterKevin时,代码会从DB中删除BradMike

array("1" => "Walter" ,
      "2" => "Kevin" ,
      "3" => "Jason" ,
      "4" => "Jimmy" ,
      "5" => "Christopher" , 
      "6" => "Bruce" , 
      "7" => "james"  );

2 个答案:

答案 0 :(得分:1)

可以使用array_shift / array_unshift,但由于逻辑似乎颠倒了,你可以使用像

这样的东西
     <?php


    $apparentDB = array("1" => "Jason" ,
          "2" => "Jimmy" ,
          "3" => "Christopher" , 
          "4" => "Bruce" , 
          "5" => "james" , 
          "6" => "Mike" ,
          "7" => "Brad" );
  /*  You can add it one by one
    $addName = "Walter";
    $apparentDB = addName($addName, $apparentDB);
    $addSecondName = "Kevin";
    $apparentDB = addName($addSecondName, $apparentDB);
*/

// Or you can also modify to work on an array of new names
    $newNames = array("Walter", "Kevin");
    foreach($newNames as $newName) {
        $apparentDB = addName($newName, $apparentDB);
    }
    var_dump($apparentDB);

    function addName($nameToAdd, $apparentDB) {

        for ($i = count($apparentDB); $i > 1; $i--) {
            $apparentDB["".$i] = $apparentDB["".($i-1)];
        }

        $apparentDB["1"] = $nameToAdd;

        //var_dump($apparentDB);
        return $apparentDB;
    }

*您可以在此处测试:http://sandbox.onlinephpfunctions.com/ *

答案 1 :(得分:0)

       $a=  array("1" => "Jason" ,
              "2" => "Jimmy" ,
              "3" => "Christopher" , 
              "4" => "Bruce" , 
              "5" => "james" , 
              "6" => "Mike" ,
              "7" => "Brad" );
      $b = array_pop($a) ;
var_dump ($a) ; // this all item without Brad ,
$b // This is Brad ; 

将元素添加到数组

array_push($a ,"New Name");