2010-04-05 52 views
0

我有一個包含了一系列的記錄像這樣的表:轉換枚舉記錄PHP對象

+-----------+--------+----------+ 
| extension | fwd_to | type  | 
+-----------+--------+----------+ 
| 800  | 11111 | noanswer | 
| 800  | 12345 | uncond | 
| 800  | 22222 | unavail | 
| 800  | 54321 | busy  | 
| 801  | 123 | uncond | 
+-----------+--------+----------+ 

查詢看起來是這樣的:

select fwd_to, type from forwards where extension='800'; 

現在我回來包含使用Kohana :: debug打印時看起來如下 的對象的數組:

(object) stdClass Object 
(
    [fwd_to] => 11111 
    [type] => noanswer 
) 

(object) stdClass Object 
(
    [fwd_to] => 12345 
    [type] => uncond 
) 

(object) stdClass Object 
(
    [fwd_to] => 22222 
    [type] => unavail 
) 

(object) stdClass Object 
(
    [fwd_to] => 54321 
    [type] => busy 
) 

我想什麼做的是轉換成這種形式的對象:

(object) stdClass Object 
(
    [busy] => 54321 
    [uncond] => 12345 
    [unavail] => 22222 
    [noanswer] => 11111 
) 

的原因是我想,然後調用它json_encode。這將允許我使用jquery populate填充表單。

有沒有建議的方法,我可以做到這一點很好?我對PHP相當陌生,我確信這很簡單,但目前它正在逃避我。

回答

0

好吧,這是我自己的答案。不知道這是否是最理想的方式,但它的工作原理。 而不是使用一個對象。我正在使用一個關聯數組,它在調用json_encode時也會得到相同的結果。

$this->template->content->call_forwarding = array(); 

$forwards = $phones->fetch_call_forwarding_numbers($this->account, $id); 
foreach($forwards as $value){ 
    $this->template->content->call_forwarding[$value->type] = $value->fwd_to; 
} 

echo Kohana::debug($this->template->content->call_forwarding); 

輸出:

(array) Array 
(
    [noanswer] => 11111 
    [uncond] => 12345 
    [unavail] => 22222 
    [busy] => 54321 
) 

然後調用json_encode結果是我後。 即echo Kohana :: debug(json_encode($ this-> template-> content-> call_forwarding));

(string) {"noanswer":"11111","uncond":"12345","unavail":"22222","busy":"54321"} 
+0

這與我的答案是一樣的,但使用關聯數組(我更喜歡順便說一句,但你問的對象)。 – rogeriopvl 2010-04-05 23:20:27

+0

是的,謝謝你。我只是意識到一個數組也可以工作。我提到我想要去json字符串,所以我可以使用jquery populate。 – Matt 2010-04-05 23:24:17

1

這是一個醜陋的黑客攻擊,但這項工作:

$newObj = new stdClass(); 
// $resultArray is the query return 
foreach($resultArray as $obj) { 
    $newObj->{$obj->type} = $obj->fwd_to; 
} 
+0

謝謝,非常類似於我剛剛在數組中形成的內容。 – Matt 2010-04-05 23:18:43