tags:

views:

28

answers:

2

I have a table containing a bunch of records like this:

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

etc

The query looks like this:

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
)

What I'd like to do is convert this to an object of this form:

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

The reason being I want to then call json_encode on it. This will allow me to use jquery populate to populate a form.

Is there a suggested way I can do this nicely? I'm fairly new to PHP and I'm sure this is easy but it's eluding me at the moment.

+1  A: 

It's a ugly hack, but does the job:

$newObj = new stdClass();
// $resultArray is the query return
foreach($resultArray as $obj) {
    $newObj->{$obj->type} = $obj->fwd_to;
}
rogeriopvl
Thanks, very similar to what I just worked out in the array form.
Matt H
A: 

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);

outputs:

(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"}
Matt H
It's the same as my answer but using an associative array (which I prefer btw, but you asked for object).
rogeriopvl
yes, thanks for that. I just realised an array would work too. I did mention that I want to go to the json string so I can use jquery populate.
Matt H