迭代控制器和树枝中的对象

时间:2014-04-16 16:03:37

标签: php json symfony twig

我正在努力研究如何在我的twig symfony2 Web服务中显示一个对象数组。能不能帮我,因为我收到了错误代码。我的问题是我无法在我的树枝中显示对象数组。 这是我的代码:

控制器:

public function InfoAction($id)
    {
        $client = new Client('https://www.googleapis.com/books/v1');
        $request = $client->get('volumes?q=id='.$id);
        $response =  $request->send();
        $content = $response->json();
        var_dump($content);
        return $this->render('BooksBookBundle:GoogleBooks:Info.html.twig', array (
          ['items' => $content['items']],
          ['books' => $content, array(
          new volumeInfo('title', 'authors','publisher'),
          new SaleInfo('country','saleability'))]
             ));

}

我要显示的Json字符串:

{
 "kind": "books#volume",
 "id": "8Pr_kLFxciYC",
 "etag": "Eyx8QAfP36s",
 "selfLink": "https://www.googleapis.com/books/v1/volumes/8Pr_kLFxciYC",
 "volumeInfo": {
  "title": "Flowers For Algernon",
  "authors": [
   "Daniel Keyes"
  ],
  "publisher": "Hachette UK",
  "publishedDate": "2012-11-15",
  "description": "Charlie Gordon, IQ 68, is a floor sweeper, and the gentle butt of everyone's jokes, until an experiment in the enhancement of human intelligence turns him into a genius. But then Algernon, the mouse whose triumphal experimental tranformation preceded his, fades and dies, and Charlie has to face the possibility that his salvation was only temporary.",
  "industryIdentifiers": [
   {
    "type": "ISBN_10",
    "identifier": "0575088494"
   },
   {
    "type": "ISBN_13",
    "identifier": "9780575088498"
   }
  ],
  "pageCount": 224,
  "printedPageCount": 328,
  "printType": "BOOK",
  "categories": [
   "Fiction / Science Fiction / General"
  ],
  "averageRating": 4.0,
  "ratingsCount": 3081,
  "contentVersion": "0.1.1.0.preview.2",
  "imageLinks": {
   "smallThumbnail": "http://bks7.books.google.co.uk/books?id=8Pr_kLFxciYC&printsec=frontcover&img=1&zoom=5&edge=curl&imgtk=AFLRE71wn80lT4uw3t25Ft3G1PFmGSb21z4aL4ZZDTl9dvDTlCKqKQFCDikPUeFgK6yg9jexlnalsIONz423vhBma2-ywTG9PdQKaCS85Q6RTtdVVORaswE&source=gbs_api",
   "thumbnail": "http://bks7.books.google.co.uk/books?id=8Pr_kLFxciYC&printsec=frontcover&img=1&zoom=1&edge=curl&imgtk=AFLRE73tDFRwijQ8sfAvU6Zv0jLLX1jXqdYaNWsensdQhfrU32cpemYTpAT25gE_ocYLTK9z5sW6UOBadpWTCR5ay1wTvXjjRRHIpjh6hCeKAibbIWe2wG8&source=gbs_api",
   "small": "http://bks7.books.google.co.uk/books?id=8Pr_kLFxciYC&printsec=frontcover&img=1&zoom=2&edge=curl&imgtk=AFLRE73T-jlqTcANz-XTotRx99HlpFSDOInRp6nxzUzQskstY09icPjU9lZIrBwLFt3sexPUSxITpgTldQB10xyJbplEMHCDqa9vbN16xXSgxRtUlSsIdYw&source=gbs_api"
  },
  "language": "en",
  "previewLink": "http://books.google.co.uk/books?id=8Pr_kLFxciYC&hl=&source=gbs_api",
  "infoLink": "http://books.google.co.uk/books?id=8Pr_kLFxciYC&hl=&source=gbs_api",
  "canonicalVolumeLink": "http://books.google.co.uk/books/about/Flowers_For_Algernon.html?hl=&id=8Pr_kLFxciYC"
 },
 "layerInfo": {
  "layers": [
   {
    "layerId": "geo",
    "volumeAnnotationsVersion": "4"
   }
  ]
 },
 "saleInfo": {
  "country": "GB",
  "saleability": "FOR_SALE",
  "isEbook": true,
  "listPrice": {
   "amount": 4.99,
   "currencyCode": "GBP"
  },
  "retailPrice": {
   "amount": 3.99,
   "currencyCode": "GBP"
  },
  "buyLink": "http://books.google.co.uk/books?id=8Pr_kLFxciYC&hl=&buy=&source=gbs_api",
  "offers": [
   {
    "finskyOfferType": 1,
    "listPrice": {
     "amountInMicros": 4990000.0,
     "currencyCode": "GBP"
    },
    "retailPrice": {
     "amountInMicros": 3990000.0,
     "currencyCode": "GBP"
    }
   }
  ]
 },
 "accessInfo": {
  "country": "GB",
  "viewability": "PARTIAL",
  "embeddable": true,
  "publicDomain": false,
  "textToSpeechPermission": "ALLOWED_FOR_ACCESSIBILITY",
  "epub": {
   "isAvailable": true,
   "acsTokenLink": "http://books.google.co.uk/books/download/Flowers_For_Algernon-sample-epub.acsm?id=8Pr_kLFxciYC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
  },
  "pdf": {
   "isAvailable": false
  },
  "webReaderLink": "http://books.google.co.uk/books/reader?id=8Pr_kLFxciYC&hl=&printsec=frontcover&output=reader&source=gbs_api",
  "accessViewStatus": "SAMPLE",
  "quoteSharingAllowed": false
 }
}

我的TWIG

{% extends "::base.html.twig" %}

{% block title %}BooksBookBundle:GoogleBooks:volumes{% endblock %}

{% block body %}
    <h1>Book Information</h1>
   {% for volumeInfo in volumeInfos %}
    {{ volumeInfo.title }}
       {% endfor %}
{% endblock %}

我的var_dump

array (size=3)
  'kind' => string 'books#volumes' (length=13)
  'totalItems' => int 1
  'items' => 
    array (size=1)
      0 => 
        array (size=8)
          'kind' => string 'books#volume' (length=12)
          'id' => string '8Pr_kLFxciYC' (length=12)
          'etag' => string 'KEN5W2AmaSo' (length=11)
          'selfLink' => string 'https://www.googleapis.com/books/v1/volumes/8Pr_kLFxciYC' (length=56)
          'volumeInfo' => 
            array (size=17)
              ...
          'saleInfo' => 
            array (size=7)
              ...
          'accessInfo' => 
            array (size=10)
              ...
          'searchInfo' => 
            array (size=1)

错误消息:

ClassNotFoundException: Attempted to load class "volumeInfo" from namespace "Books\BookBundle\Controller" in /Users/prezequias/Desktop/santosbookreview/src/Books/BookBundle/Controller/GoogleBooksController.php line 31. Do you need to "use" it from another namespace?

变量书是我创造的,也许我错了。

感谢您的提前帮助

2 个答案:

答案 0 :(得分:0)

您实际上并没有将volumeInfos变量传递给模板,但是您传递的是“books”数组。

尝试类似:

{% for book in books %}
    {{ book.volumeInfo['title'] }} // Might not be the right syntax but the idea is to iterate over "books"
{% endfor %}

我不确定你对书籍的定义,你看到了什么错误信息?

答案 1 :(得分:0)

您尝试实例化一个PHP类VolumeInfo,但这个PHP类不存在!

解决方案:

控制器:

$items = $content->items;
return $this->render('BooksBookBundle:GoogleBooks:Info.html.twig', array ('items'=>$items));

模板:

{% for item in items %}
    Title : {{ item.volumeInfo.title }}<br>
    Author : 
    {% for author in item.volumeInfo.authors %}
       {{ item.volumeInfo.authors[0] }}
    {% endfor %}
{% endfor %}

或者,如果您总是有一本书,则可以直接将该书传递给模板:

控制器:

$items = $content->items[0];
return $this->render('BooksBookBundle:GoogleBooks:Info.html.twig', array ('item'=>$item));