我對這個類有問題,特別是最後兩個函數callApi($query)
和objectToArray($d)
。這些目標是從Amazon API返回的對象中返回數組。將stdObject轉換爲數組 - 調用函數
我認爲這個問題是從另一個這裏調用一個函數:
$arrayResponse=$this->objectToArray($response);
即使我這樣做時,我的var_dump $arrayResponse
我仍然把它作爲一個對象,不能執行數組具體操作(廢話; ))。我在this site和Amazon Library上找到了objectToArray()
。
當我單獨測試它時,它工作正常,但在將其放入項目後,我仍然得到該對象。
難道是我只是以錯誤的方式調用函數,所以它不會轉換它?
謝謝你在前進,
亞當
class Amazon extends Source implements ICallsApi{
function __construct(){
$this->impact = 55;
$this->side = "supply";
echo "<p>I am Amazon</p>";
echo "<p>and my impact = ". $this->impact."</p>";
}
private function FormulateQuery($query){
echo "Formulate query for Amazon API and return it";
}
//Returns the array records from amazon of a given keyword
public function callApi($query)
{
$client = new AmazonECS('dataRemoved', 'dataRemoved', 'co.uk', 'dataRemoved');
$response = $client->category('Books')->search($query);
//var_dump($response);
//echo "<pre>";
//print_r($response);
//echo "</pre>";
$arrayResponse=$this->objectToArray($response);
var_dump($arrayResponse);
//echo "<pre>";
//print_r($arrayResponse);
//echo "</pre>";
echo "code returns an array of results";
// return $arrayResponse;
} //objectToArray($d) found online
public function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$this->d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
}
感謝@FAngel 得到了如下回應 「警告:array_map()預計參數1是一個有效的回調,功能‘objectToArray’未找到或無效函數名稱在線151上的C:\ xampp \ htdocs \ msc \ SourcesClasses.php中012elNULL代碼返回結果數組' 第151行'return array_map(__ FUNCTION__,$ d);' –
把它放在課外或看看這個[page](http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback)。坦率地說,從來沒有試圖做這樣的事情,但據我所知,你需要用'return array_map(array($ this,'objectToArray'),$ d);' –
'替換'return array_map(__ FUNCTION__,$ d)謝謝@ FAngel, 我認爲我們正在接近 - 這種改變fynction返回對象數組,但我真正需要的是一個正常的關聯數組,這是由我在第一篇文章鏈接到的測試代碼輸出(亞馬遜圖書館和功能網站)。任何想法的修復? Best,Adam –