我正在調用JSON文件中的數據。我的一個元素是:將變量設置爲從JSON清空,不返回null
"mainImg_select":""
有時候這有一個值,有時候它不會 - 在這種情況下它是空的。我把這個(以及其他)變量放在一個名爲Product的對象中。
當試圖設置$product -> mainImg
時,我試圖查看JSON值是否爲空。如果它是空的,我想獲得另一組圖像的第一個值,$more_imgs
並將其作爲主圖像。這裏是我的代碼:
if(!is_null($mainImg)) {
$product->mainImage = $html->find($mainImg, 0)->src;
for ($idx = 0; $idx < 10; $idx++) {
$more = $html->find($more_imgs, $idx);
if (!is_null($more)) {
$product->moreImages[$idx] = $more->src;
} else {
return;
}
}
} else {
for ($idx = 0; $idx < 10; $idx++) {
$more = $html->find($more_imgs, $idx);
if (($idx == 0) && (!is_null($more))) {
$product->mainImage = $more->src;
} elseif (!is_null($more)) {
$product->moreImages[$idx] = $more->src;
} else {
return;
}
}
}
當我運行代碼,我的關係得到Notice: Trying to get property of non-object
到$product->mainImage = $html->find($mainImg, 0)->src;
我認爲這事做與if(!is_null($mainImg))
它上面,因爲在定義$ mainImg爲空JSON。如果不是,這裏最好用什麼?
編輯:這是當產品對象被設定一些更詳細代碼: http://pastebin.com/EEUgpwgn
變量'$ html'的類型是什麼?首選'if(!empty($ mainImg))'條件來測試您的值是否爲空或空值。 – antoox
HTML由$ html = str_get_html(curl($ infoLink))設置;''其中'$ infoLink'是一個URL。 – Jascination
非對象表示「$ product」或「$ html」不是對象。 – RMcLeod