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


Writing out every title from a search result from an API

我正在使用一个配方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"},

如果需要一个标题列表,可以使用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;