我有一个包含大量记录的表:
+-----------+--------+----------+
| 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 :(得分:1)
这是一个丑陋的黑客,但做的工作:
$newObj = new stdClass();
// $resultArray is the query return
foreach($resultArray as $obj) {
$newObj->{$obj->type} = $obj->fwd_to;
}
答案 1 :(得分: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"}