2013-05-16 58 views
0

我正在調用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

+0

變量'$ html'的類型是什麼?首選'if(!empty($ mainImg))'條件來測試您的值是否爲空或空值。 – antoox

+0

HTML由$ html = str_get_html(curl($ infoLink))設置;''其中'$ infoLink'是一個URL。 – Jascination

+0

非對象表示「$ product」或「$ html」不是對象。 – RMcLeod

回答

1

你應該改變!is_null!empty因爲即使 「mainImg_select」 is_null()將返回false等於空字符串「」。

1

無論$mainImg在HTML中沒有找到;代碼$html->find($mainImg, 0)將返回null,然後您將嘗試訪問null對象的src參數。

(從Documentation of the php simple HTML Parser Library

// Find (N)th anchor, returns element object or null if not found (zero based) 
$ret = $html->find('a', 0); 

你必須這樣做:

if (null !== ($img = $html->find($mainImg, 0))) { 
    $imgSrc = $img->src; // Here the HTML Element exists and you can access to the src parameter 
}