JSON字符串添加链接

时间:2012-01-20 09:19:16

标签: php html json

我有一个返回JSON字符串的php:

$recipes = json_encode($arr);

这是我的php代码我如何输出食谱标题:

<?php
 include('php/getAllRecipes.php');
 $jsonstring = $recipes;
 $recip = json_decode($recipes, true);
 $i = 1;
 var data = include('php/getAllRecipes.php')Data.Recipes;
foreach ($recip['Data']['Recipes'] as $key => $recipe) {
        echo "$i.) &nbsp ";
        echo  $recipe['TITLE'];
        $i = $i + 1;
        echo "<br>";
 } 
 ?>

现在,我需要为每个标题添加一个href。 href应该包含recipe_search.php的链接,我必须给它每个食谱的ID。 我怎样才能添加这个href?

2 个答案:

答案 0 :(得分:1)

你在......

foreach ($recip['Data']['Recipes'] as $key => $recipe)
{
    // I guess $key is ID of your recipe...
    echo  sprintf('%d.) <a href="%s">%s</a><br />', $i++, 'recipe_search.php?id=' . $key, $recipe['TITLE']);
}

这对我有用,只是为了测试上面的内容:

<?php
    $i = 1;
    foreach (array_fill(0, 40, 'recipe') as $key => $recipe)
    {
        // I guess $key is ID of your recipe...
        echo  sprintf('%d.) <a href="%s">%s</a><br />', $i++, 'recipe_search.php?id=' . $key, $recipe);
    }
?>

答案 1 :(得分:1)

<?php
 include('php/getAllRecipes.php');
 $jsonstring = $recipes;
 $recip = json_decode($recipes, true);
?>
<ol>
<?php
foreach ($recip['Data']['Recipes'] as $key => $recipe) {
        echo '<li>
                  <a href="/recipe_search.php?id=' . $recipe['ID'] . '">
                      ' . $recipe['TITLE'] . '
                  </a>
              </li>';
 } 
 ?>
</ol>
  1. 使用有序列表(<ol>)而不是尝试使用计数器创建一个。
  2. var data = include('php/getAllRecipes.php')Data.Recipes;无效PHP。
  3. 我假设食谱的ID在$recipe['ID']