Я пытаюсь вернуть все ответы на каждый вопрос из Yahoo API, и сейчас мой код ...

    $appid= "myid";
    $params = array(
'query'     =>      $keyword,   //enter your keyword here. this will be searched on yahoo answer
'results'   =>      $maxLimit,         //number of questions it should return
'type'      =>      'resolved',  //only resolved questiosn will be returned. other values can be all, open, undecided
'output'    =>      'php',      //result will be PHP array. Other values can be xml, json, rss
);
$yn = new yahooAnswer($appid);
//search questions
try
{
    $questions = $yn->search_questions($params);
} catch (Exception $e)
{
    echo ($e->getMessage());
}

foreach ($questions as $question) 
{
//now get the answers for the question_id;
    try
    {
        $answers = $yn->get_question(array('question_id'=>$question['id']));
        //print out what you would like...All fields are location on this site http://developer.yahoo.com/answers/V1/getQuestion.html
        print_r($answers);

        //print_r( $answers['NumAnswer']);
        //print_r( $answers['Content'] . "<br/>");

        //print_r($answers['chosenanswer'] . "<br/>");
        //echo $answers['UserNick']. "<br />";

        echo "<hr>";
    } catch (Exception $e)
    {
        echo($e->getMessage());
    }

}

И я получаю это как возврат, когда печатаю_r ($ answers) ...

    Array
    (
[id] => 20090408072929AAbYFdK
[type] => Answered
[Subject] => Do you like apples???????????
[Content] => Just wanted to know how many people really like apples out there.

[Date] => 2009-04-08 07:29:29
[Timestamp] => 1239175769
[Link] => http://answers.yahoo.com/question/?qid=20090408072929AAbYFdK
[Category] => Array
    (
        [id] => 396545372
        [content] => Other - Food & Drink
    )

[UserId] => l3ja8nMSaa
[UserNick] => Bob
[UserPhotoURL] => http://l.yimg.com/sc/28232/answers1/images/a/i/identity/nopic_48.png
[NumAnswers] => 10
[NumComments] => 0
[ChosenAnswer] => apples are delish
    i luv the dark red apples
    the green ones
    apple sauce
    apple pie (with vanilla ice cream)
[ChosenAnswererId] => ihAFSbClaa
[ChosenAnswererNick] => SantaFe95
[ChosenAnswerTimestamp] => 1239176570
[ChosenAnswerAwardTimestamp] => 1240818783
[Answers] => Array
    (
        [0] => Array
            (
                [Content] => Apples are my second favourite fruit.
                [Reference] => 
                [Best] => 
                [UserId] => rZMc7vTXaa
                [UserNick] => gemstone
                [Date] => 2009-04-08 07:36:21
                [Timestamp] => 1239176181
            )

        [1] => Array
            (
                [Content] => when i was little i used to love them because they were very hard          to find where we lived and hardly ever got to eat any.
            then when i grew up and had to go on a diet where i had to eat 5 or 6 a day i learned to hate them.
                [Reference] => 
                [Best] => 
                [UserId] => aecb87753b7a91041ba0f8e18327da41aa
                [UserNick] => Missy ~
                [Date] => 2009-04-08 07:36:38
                [Timestamp] => 1239176198
            )

        [2] => Array
            (
                [Content] => Yep - granny smith, braeburn, and honeycrisp are my favorites
                [Reference] => 
                [Best] => 
                [UserId] => 9LYQ34Bvaa
                [UserNick] => sportslover7
                [Date] => 2009-04-08 07:36:45
                [Timestamp] => 1239176205
            )

        [3] => Array
            (
                [Content] => apples are awesome. But, I can't eat them cold, my teeth are WAY TOO sensitive.
                [Reference] => 
                [Best] => 
                [UserId] => l63HXU7kaa
                [UserNick] => Kira
                [Date] => 2009-04-08 07:39:33
                [Timestamp] => 1239176373
            )

        [4] => Array
            (
                [Content] => GALA APPLES
                [Reference] => 
                [Best] => 
                [UserId] => tsad330Maa
                [UserNick] => Lie T
                [Date] => 2009-04-08 07:40:58
                [Timestamp] => 1239176458
            )

        [5] => Array
            (
                [Content] => Of course.  But I only get organic apples.  Regular apples are on         the "dirty dozen" list for being sprayed with loads pesticides and chemicals...yuck!
                [Reference] => 
                [Best] => 
                [UserId] => 1939a4787cfedfac7deb18c16c99dde2aa
                [UserNick] => Jami J
                [Date] => 2009-04-08 07:42:03
                [Timestamp] => 1239176523
            )

        [6] => Array
            (
                [Content] => apples are delish
    i luv the dark red apples
    the green ones
    apple sauce
    apple pie (with vanilla ice cream)
                [Reference] => 
                [Best] => 5
                [UserId] => ihAFSbClaa
                [UserNick] => SantaFe95
                [Date] => 2009-04-08 07:42:50
                [Timestamp] => 1239176570
            )

        [7] => Array
            (
                [Content] => OMG I love Granny Smith Apples (You know, the green ones)
                [Reference] => 
                [Best] => 
                [UserId] => yIiKFxU5aa
                [UserNick] => That half-black half-white girl
                [Date] => 2009-04-08 07:50:20
                [Timestamp] => 1239177020
            )

        [8] => Array
            (
                [Content] => yeah
                [Reference] => 
                [Best] => 
                [UserId] => AA11402528
                [UserNick] => Wambo
                [Date] => 2009-04-08 07:58:26
                [Timestamp] => 1239177506
            )

        [9] => Array
            (
                [Content] => i love apples ! An apple a day keeps the doctor away the trick it to hit him on the head with it
                [Reference] => 
                [Best] => 
                [UserId] => ElxlHvL5aa
                [UserNick] => blindartist47
                [Date] => 2009-04-08 08:15:05
                [Timestamp] => 1239178505
            )

    )

)

Но когда я использую print_r (answers ['Content']), я распечатываю только один из них, а не все. Есть идеи, как решить эту проблему? Должно быть напечатано шесть ответов

0
John Smith 8 Мар 2014 в 14:58

1 ответ

Лучший ответ

Это потому, что массив содержит новый Массив ответов с именем ['Answers']. Поэтому, если вы хотите распечатать каждый полученный ответ, вам нужно будет сделать следующее:

try
{
    $answers = $yn->get_question(array('question_id'=>$question['id']));
    //print out what you would like...All fields are location on this site http://developer.yahoo.com/answers/V1/getQuestion.html
    foreach($answers['Answers'] as $answer)
    {
      print_r($answer['Content']);
      echo "<hr>";
    }
}
catch (Exception $e)
{
    echo($e->getMessage());
}

E: Когда вы выгружаете массив с помощью print_r() или var_dump(), всегда завершайте результат в pretags, чтобы вы могли легко увидеть, что вложено в новый массив и т. Д.

echo "<pre>";
print_r($answers);
echo "</pre>";
0
Johnny000 6 Ноя 2016 в 14:44
Я пробовал это, но все еще не работает, я также редактировал вопрос
 – 
John Smith
8 Мар 2014 в 15:22
Сделана опечатка в названии массива. Обновил код. Пытаться :)
 – 
Johnny000
8 Мар 2014 в 15:23