gpt4 book ai didi

php - unset() 在类方法中不起作用

转载 作者:可可西里 更新时间:2023-10-31 23:28:57 29 4
gpt4 key购买 nike

我有一个类 Foo,它有一个名为 barjson 字符串属性:[PHP Fiddle Link]

<?php


class Foo {

public $bar = '{"1455260079":"Tracking : #34567808765098767 USPS","1455260723":"Delivered","1455261541":"Received Back"}';

public function getBar(){
return (array) json_decode($this->bar);
}

public function remove($timestamp){

$newBar = $this->getBar();

print_r($newBar);

unset($newBar[$timestamp]);

print_r($newBar);

$this->bar = json_encode($newBar);

}

}

现在,要从栏中删除一个元素,我正在执行以下操作,我不明白为什么它没有删除:

$foo = new Foo();
$foo->remove("1455261541");
echo $foo->bar;

打印出来:

Array
(
[1455260079] => Tracking : #34567808765098767 USPS
[1455260723] => Delivered
[1455261541] => Received Back
)
Array
(
[1455260079] => Tracking : #34567808765098767 USPS
[1455260723] => Delivered
[1455261541] => Received Back
)
{"1455260079":"Tracking : #34567808765098767 USPS","1455260723":"Delivered","1455261541":"Received Back"}

这背后的原因是什么?有帮助吗?

最佳答案

尝试下面的解决方案,我只是更改了 getBar 函数并在 json_decode 函数中添加了一个参数:

class Foo {

public $bar = '{"1455260079":"Tracking : #34567808765098767 USPS","1455260723":"Delivered","1455261541":"Received Back"}';

public function getBar(){
return json_decode($this->bar, true);
}

public function remove($timestamp){

$newBar = $this->getBar();

print_r($newBar);

unset($newBar[$timestamp]);

print_r($newBar);

$this->bar = json_encode($newBar);

}

}

$foo = new Foo();
$foo->remove("1455261541");
echo $foo->bar;

输出:

Array
(
[1455260079] => Tracking : #34567808765098767 USPS
[1455260723] => Delivered
[1455261541] => Received Back
)
Array
(
[1455260079] => Tracking : #34567808765098767 USPS
[1455260723] => Delivered
)
{"1455260079":"Tracking : #34567808765098767 USPS","1455260723":"Delivered"}

关于php - unset() 在类方法中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35357703/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com