2012-07-15 48 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