4

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?

tika
  • 7,135
  • 3
  • 51
  • 82

1 Answers1

2

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"}
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
  • Hmm, that works cool! It's so strange that we cannot unset a damn array with keys! Thanks. – tika Feb 12 '16 at 08:21
  • 1
    array type casting using `(array)` will convert keys into string see the var_dump of array in your original code – Chetan Ameta Feb 12 '16 at 08:27