2013-01-18 58 views
-1

搜索我在格式通過JSON與PHP

{ 
    "list" : { 
      "1" : { 
       "thing1" : "description", 
       "thing2" : "description", 
       "thing3" : "description" 
      }, 
      "2" : { 
       "thing1" : "description", 
       "thing2" : "description", 
       "thing3" : "description" 
      }, 
      etc. 

} 

我需要通過搜索和返回基於東西2描述數據,但我也需要再返回列表的數量JSON文件。問題是json文件全部出現亂碼,所以我不能只是在我遍歷所有變量時增加一個變量。

目前我有我的代碼的設置是這樣的:

$json = json_decode($response); 
foreach($json->list as $item) { 
     $i++; 
     if($item->thing2 == "description") { 
      echo "<p>$item->thing1</p>"; 
      echo "<p>$item->thing2</p>"; 
      echo "<p>$item->thing3</p>"; 
      echo "<p>position: $i</p><br /><br />"; 
     } 
    } 

不幸的是,因爲位置是無序每次$ i變量被重新調整了錯誤的位置。我該如何返回具有正確描述的物品的標題。

回答

0

設置json_decode()TRUE返回一個關聯數組這是一個有點更有利於你想要做什麼的第二個參數:

$json = json_decode($response, TRUE); 
foreach($json['list'] as $key => $item) { 
    if($item['thing2'] == "description") { 
     echo "<p>$item['thing1']</p>"; 
     echo "<p>$item['thing2']</p>"; 
     echo "<p>$item['thing3']</p>"; 
     echo "<p>position: $key</p><br /><br />"; 
    } 
} 

應該做的伎倆。

+0

雖然很高興提及關聯數組參數,但這裏並不需要它。 。 。 foreach將像數組一樣輕鬆地遍歷對象。 – ernie

2

變化

foreach($json->list as $item) { 
    $i++; 

foreach($json->list as $i => $item) { 

(這是PHP文檔中用於描述object iteration

-1

json_decode具有返回關聯數組($assoc = true)的選項。在此之後,訪問$associative_array["2"]是微不足道的。