2012-07-15 62 views
0

我正在使用一些由OpenLibrary.org製作的json,並從info重新創建一個新數組。 Link to the OpenLibrary jsonPHP重寫一個json數組(undefined offset)

這裏是我的PHP代碼的JSON解碼:

$barcode = "9781599953540"; 

function parseInfo($barcode) { 
    $url = "http://openlibrary.org/api/books?bibkeys=ISBN:" . $barcode . "&jscmd=data&format=json"; 
    $contents = file_get_contents($url); 
    $json = json_decode($contents, true); 
    return $json; 
} 

新的陣列我試圖做看起來是這樣的:

$newJsonArray = array($barcode, $isbn13, $isbn10, $openLibrary, $title, $subTitle, $publishData, $pagination, $author0, $author1, $author2, $author3, $imageLarge, $imageMedium, $imageSmall); 

,但是當我試圖讓在ISBN_13將其保存到$網路書店,我得到一個錯誤:

Notice: Undefined offset: 0 in ... on line 38 
// Line 38 
$isbn13 = $array[0]['identifiers']['isbn_13']; 

即使我嘗試$ array [1],[2],[3] ....我也會得到同樣的結果。我在這裏弄錯了什麼!哦,我知道我的寶貴名字可能不一樣,那是因爲它們有不同的功能。

感謝您的幫助。

+1

'$ array'中包含什麼? '的var_dump($陣列)'。在你的代碼中,你填充'$ json',而不是'$ array'。 – 2012-07-15 14:11:37

+0

該數組可能是由字符串鍵索引的,而不是整數。另外,$ array在哪裏顯示? – Novak 2012-07-15 14:12:16

+1

@GuyDavid或者如果它的原點是JSON,它們可能是對象屬性。 – 2012-07-15 14:13:19

回答

2

你的陣列是不是用整數索引,它是由ISBN號索引:

Array 
(
    // This is the first level of array key! 
    [ISBN:9781599953540] => Array 
     (
      [publishers] => Array 
       (
        [0] => Array 
         (
          [name] => Center Street 
         ) 

       ) 

      [pagination] => 376 p. 
      [subtitle] => the books of mortals 
      [title] => Forbidden 
      [url] => http://openlibrary.org/books/OL24997280M/Forbidden 
      [identifiers] => Array 
      (
       [isbn_13] => Array 
        (
         [0] => 9781599953540 
        ) 

       [openlibrary] => Array 
        (
         [0] => OL24997280M 
        ) 

所以,你需要通過第一ISBN調用它,關鍵isbn_13本身,你必須訪問數組通過元素:

// Gets the first isbn_13 for this item: 
$isbn13 = $array['ISBN:9781599953540']['identifiers']['isbn_13'][0]; 

或者,如果你需要在許多人的一個循環:

foreach ($array as $isbn => $values) { 
    $current_isbn13 = $values['identifiers']['isbn_13'][0]; 
} 

如果您希望只有一個每次都必須能夠獲得其關鍵不知道它的時間提前,但不希望一個循環,你可以使用array_keys()

// Get all ISBN keys: 
$isbn_keys = array_keys($array); 
// Pull the first one: 
$your_item = $isbn_keys[0]; 
// And use it as your index to $array 
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0]; 

如果你有PHP 5.4,你可以通過數組引用跳過一步!:

// PHP >= 5.4 only 
$your_item = array_keys($array)[0]; 
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0]; 
+0

我明白了,但問題是任何時候$ barcode的變化,['ISBN:9781599953540']也會改變。我需要使我的代碼動態。無論如何用array_keys()來完成它。對不起,PHP很新。仍在學習。 – Throdne 2012-07-15 14:20:21

+0

@Throdne你是否只希望每次都回來一件物品? – 2012-07-15 14:21:27

+0

@Throdne在這裏查看'array_keys()'的用法。 – 2012-07-15 14:23:22