从API的搜索结果中写出每个标题

时间:2015-05-15 19:06:46

标签: php api foreach

我正在使用配方API,我设法使用书面搜索词编写每个食谱,我不能使用$contentSearch->recipes->title写出标题,但我需要一个foreach循环,我猜,把每个冠军都拿出来。但是我没有让它发挥作用。

那么,如何从搜索结果中写出每个标题?

下面我的代码不包含我对此问题的尝试,因为我猜我太远了。

   $apiUrl = "http://food2fork.com/api/search?key=" . $apiKey . "&q=". $search ;


    // get the content of the file
    $contentSearch = json_decode(file_get_contents($apiUrl));

    $allRecipes =  json_encode($contentSearch->recipes);

    return $allRecipes;

当编写上面的代码时,我得到的结果是(前两个例子):

[{"publisher":"Closet Cooking",
"title":"Bacon Wrapped Jalapeno Popper Stuffed Chicken",
"recipe_id":"35120"},
{"publisher":"Closet",
"title":"Buffalo Chicken Chowder",
"recipe_id":"35169"},

1 个答案:

答案 0 :(得分:0)

如果你想要一个标题列表,你可以使用array_map轻松完成。这是一个完整的例子(带有一些JSON的虚拟文本)

<?php
//Just some dummy text
$jsonString = <<<JSON
[{"publisher":"Closet Cooking",
"title":"Bacon Wrapped Jalapeno Popper Stuffed Chicken",
"recipe_id":"35120"},
{"publisher":"Closet",
"title":"Buffalo Chicken Chowder",
"recipe_id":"35169"}]
JSON;

//decode the json (just like you're doing)
$jsonArr = json_decode($jsonString);

//loop over the titles and write it out like you asked
foreach($jsonArr as $recipe) {
        echo $recipe->title;
}

// but I noticed you also have a return so maybe you just want to return the titles?
function getTitle($recipeObj) {
        return $recipeObj->title;
}

// return a list of titles by mapping the getTitle function across the array of objects
return array_map(getTitle, $jsonArr);

请注意,您不必使用array_map,如果您对此更容易理解,您可以轻松地执行此类操作:

$titles = array();
foreach($jsonArr as $recipe){
     $titles[] = $recipe->title;
}
return $titles;