Php nesneye numaralandırılmış kayıtları dönüştürebilirsiniz

2 Cevap php

Bu gibi kayıtların bir demet içeren bir tablo var:

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

vb

Sorgu bu gibi görünüyor:

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

Now I get back an array containing objects which look like the following when printed with 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
)

Ne yapmak istiyorum, bu formun bir nesne için bu dönüştürmek:

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

Ben bunun üzerine json_encode aramak istediğiniz olma nedeni. Bu bana bir formu doldurmak için jquery populate kullanmanızı sağlayacak.

Ben güzel yapabilirim önerilen bir yolu var mı? PHP oldukça yeni ve ben bu kolaydır eminim ama şu anda beni aklına gelmiyor.

2 Cevap

Ok, this is my own answer. Not sure if it's the most optimal way but it works. Instead of using an object. I'm using an associative array which will also give the same result when calling 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);

çıkışlar:

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

Then calling json_encode the result is what I'm after. i.e. echo Kohana::debug(json_encode($this->template->content->call_forwarding));

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

Bu bir çirkin kesmek, ama iş yok:

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