我正在使用CodeIgniter 2.2.6 + DataMapper,我有一个关于如何将存储过程的结果转换为DataMapper模型的问题,然后将它们转换为json。
我有一个名为Event的模型:
class Event extends DataMapper {
var $table = 'EVENT'; // map to EVENT table
}
使用以下代码,我可以轻松获得前10名的事件:
$event = new Event();
$event->get( 10, 0 );
$event->all_to_json(); //this convert the result to json following the table structure
现在我有一个存储过程getSpecialEvent(),此SP的结果与表EVENT具有完全相同的结构,
使用以下代码,我确实得到了内容,但它们是数组格式:
$sql = "call getSpecialEvent()";
$event = new Event();
$event = $this->db->query ($sql);
print_r ($event->result_array());
这会返回一些像这样的东西:
Array
(
[0] => Array
(
[event_id] => 11
[title] => Test1
...
)
[1] => Array
(
[event_id] => 2
[title] => Test1
...
)
)
如果我使用这个
foreach ( $event as $obj ) {
print_r($obj);
}
我得到空数组:
Array
(
)
Array
(
)
然后我试了
print_r ($event->result());
它返回
Array
(
[0] => stdClass Object
(
[event_id] => 11
[title] => Test1
...
)
[1] => stdClass Object
(
[event_id] => 2
[title] => Test2
...
)
}
我使用了一些在互联网上找到的代码将stdClass对象转换为Event,看起来好像,但是当我调用to_json()方法时,它不起作用。
function objectToObject($instance, $className) {
return unserialize(sprintf(
'O:%d:"%s"%s',
strlen($className),
$className,
strstr(strstr(serialize($instance), '"'), ':')
));
}
foreach ( $event->result() as $obj ) {
$newObj = $this->objectToObject($obj, "Event");
print_r ($newObj);
print_r ($newObj->to_json());
}
我打印了他铸造的物品,这里是:
Event Object
(
[table] => EVENT
[error] =>
[stored] =>
[model] =>
[primary_key] => id
[valid] =>
[cascade_delete] => 1
[fields] => Array
(
)
[all] => Array
(
)
[parent] => Array
(
)
[validation] => Array
(
)
[has_many] => Array
(
)
[has_one] => Array
(
)
[production_cache] =>
[free_result_threshold] => 100
[default_order_by] =>
[_validated:protected] =>
[_force_validation:protected] =>
[_instantiations:protected] =>
[_field_tracking:protected] =>
[_query_related:protected] => Array
(
)
[_include_join_fields:protected] =>
[_force_save_as_new:protected] =>
[_where_group_started:protected] =>
[_group_count:protected] => 0
[event_id] => 11
[title] => test11
...
)
但$ newObj-> to_json()返回空
Array
(
)
Array
(
)
如果我做一个小测试
$event = new Event ();
$event->event_id = 13;
$event->title = "xxxxx";
echo json_encode($event->to_json());
我明白了:
{"event_id":13,"title":"xxxxx"....}
我不知道为什么演出的对象不适用于to_json?
答案 0 :(得分:0)
这似乎是一个限制,铸造的DataMapper对象(这里的Event)不是一个真正的DataMapper对象,然后我在Event中创建一个方法,将所需的信息导出到另一个纯对象模型并使用json_encode(),这很有效。