2016-02-12 49 views
3

我有一個類說,Foo有一個名爲bar一個json字符串屬性裏面不工作:[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"} 

背後的原因是什麼?任何幫助?

回答

2

嘗試下面的解決方案,我只是改變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"} 
+0

嗯,這作品很酷!這很奇怪,我們不能用鑰匙來解除一個該死的陣列!謝謝。 – tika

+1

使用'(array)'進行數組類型轉換會將鍵轉換爲字符串請參閱原始代碼中的var_dump數組 –