我正在尝试将第三方API(用于与OpenSecrets.org数据进行交互)集成到我的Codeigniter站点中,并且即使变量是数组,也要保持关于将对象视为字符串的错误。
原始api可在此处找到:https://github.com/bpilkerton/php-crpapi/blob/master/crpapi.php。
我的修改可在此处找到:http://pastebin.com/HmZyhQJR。
我修改了类,以便文件名和类声明匹配,并且都有大写字母,并且我修改了构造函数,以便它只接受一个参数数组,这些参数是在调用类时设置的。我的控制员。
我修改后的代码的相关部分如下。我得到私有函数loadParams的第一行和该函数中的foreach循环的错误。第一个错误是:
Object of class stdClass could not be converted to string
第二个是:
Invalid argument supplied for foreach()
自定义类:
class Crp {
function __construct($params) {
$this->apikey = "a04a90aa18e9e482b3ff2318d313db53";
$this->baseurl = "http://api.opensecrets.org/";
$this->output = "json";
//Allow output type to be overridden on object instantiation
$this->output = isset($params['output']) ? $params['output']: $this->output;
$this->method = $params['method'];
self::loadParams($params);
/*$this->fileHash = md5($method . "," . implode(",",$params));
$this->cacheHash = "dataCache/" . $this->fileHash;
$this->cacheTime = 86400; #one day*/
}
private function loadParams($params) {
$this->url = $this->baseurl . "?method=" . $this->method .
"&apikey=" . $this->apikey;
foreach ($params as $key=>$val) {
$this->url .= "&" . $key . "=" . $val;
$this->$key = $val;
}
return;
}
控制器中的呼叫
$crp_id = $this->_getRefId($id,'indiv','crp');
$this->load->library('crp',array("method" => "candContrib","cid"=> $crp_id,"cycle"=>"2010","output"=>"json"));
// grabs the CRP id from my reference table; have tested and correctly returns string
function _getRefId($id,$type,$src)
{
switch ($src) {
case 'crp':
$field = 'ref_id as id';
break;
}
switch ($type) {
case 'indiv':
$this->db->select($field);
$this->db->where('ref_id',$id);
$query = $this->db->get('my_ref_table');
if($query->num_rows() > 0)
{
$query = $query->row();
return $query->id;
}
break;
case 'org':
break;
}
}
从我理解在CI中创建自定义库的方式来看,这就是我将参数数组传递给新实例化的方式,它只接受一个数组。有什么想法吗?
答案 0 :(得分:1)
似乎在我的设置中正常工作。你可能在$ crp_id上使用一个对象吗?你也可以发布控制器的代码吗?
编辑:我为$ crp_id插入了一个stdClass对象并得到了完全相同的第一个错误。
编辑:
switch ($type) {
case 'indiv':
$this->db->select($field);
$this->db->where('ref_id',$id);
$query = $this->db->get('my_ref_table');
if($query->num_rows() > 0)
{
$query = $query->row();
var_dump($query->id);
return $query->id;
}
return '';
break;
case 'org':
return '';
break;
}