删除变量内的数组

时间:2018-05-24 13:59:03

标签: php arrays variables

在我的内容管理系统中,变量$data输出以下内容:

Array ( [name] => last_visit [value] => 1211809129 [expire] => 1558705129 [domain] => [path] => / [prefix] => exp_ [httponly] => 1 [secure_cookie] => 0 ) 
Array ( [name] => last_activity [value] => 1527169129 [expire] => 1558705129 [domain] => [path] => / [prefix] => exp_ [httponly] => 1 [secure_cookie] => 0 ) 
Array ( [name] => csrf_token [value] => e39fe1edcd0bc48a6e35985069a [expire] => 1527176329 [domain] => [path] => / [prefix] => exp_ [httponly] => 1 [secure_cookie] => 0 ) 

我需要修改变量,删除一个数组,例如第二个数组,其名称为'last_activity'。

由于数组没有密钥,因此无法选择删除密钥。

我以为我可以使用unset,例如:

unset($data[1]);

但这不起作用。

如何从变量中删除数组?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

foreach ($data as $key => $value)
{
    if ($value['name'] === 'last_activity') {
        unset($data[$key]);
    }
}

答案 1 :(得分:0)

使用array_splice

<?php
$data = array();
$data[] = ['name' => 'last_visit', 'value' => '1211809129', 'expire' => '1558705129', 'domain' => '', 'path' => '/', 'prefix' => 'exp_', 'httponly' => 1, 'secure_cookie' => 0];
$data[] = ['name' => 'last_activity', 'value' => '1527169129', 'expire' => '1558705129', 'domain' => '', 'path' => '/', 'prefix' => 'exp_', 'httponly' => 1, 'secure_cookie' => 0 ];
$data[] = ['name' => 'csrf_token', 'value' => 'e39fe1edcd0bc48a6e35985069a', 'expire' => '1527176329', 'domain' => '', 'path' => '/', 'prefix' => 'exp_', 'httponly' => 1, 'secure_cookie' => 0];

var_dump($data);

for($i = 0; $i < sizeof($data); $i++){
    if($data[$i]['name'] == 'last_activity'){
            array_splice($data, $i, $i);
    }
}

var_dump($data);
?>