I have a class say, Foo
that has a json
string property named bar
: [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);
}
}
Now, to remove an element from bar, I am doing the following, I cannot figure out why it it not deleting:
$foo = new Foo();
$foo->remove("1455261541");
echo $foo->bar;
prints out:
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"}
What's the reason behind this? Any help?
try below solution, i just changed getBar
function and added one more parameter in json_decode
function:
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;
output:
Array
(
[1455260079] => Tracking : #34567808765098767 USPS
[1455260723] => Delivered
[1455261541] => Received Back
)
Array
(
[1455260079] => Tracking : #34567808765098767 USPS
[1455260723] => Delivered
)
{"1455260079":"Tracking : #34567808765098767 USPS","1455260723":"Delivered"}