1

Am new to Smarty, i have a json array, my json array looks like following format

[
    {
        "id": "1",
        "venue": "Test Venue1",
        "game_date": "0000-00-00 00:00:00"
    },
    {
        "id": "2",
        "venue": "Test Venue 2",
        "game_date": "0000-00-00 00:00:00"
    }
]

Tried

{foreach from=$gamearray key=k item=v}
            <li>{$k}: {$v}</li>
        {/foreach}

Its display like this way

0: [
    {
        "id": "1",
        "venue": "Test Venue1",
        "game_date": "0000-00-00 00:00:00"
    },
    {
        "id": "2",
        "venue": "Test Venue 2",
        "game_date": "0000-00-00 00:00:00"
    }

]

I just want to show venue field only.

My php looks like this way

  $stmt = $this->core->dbh->query($sql);
            $listgame = $stmt->fetchAll(PDO::FETCH_OBJ);
            $game_array = json_encode($listgame);
$app->render('base.tpl', array('gamearray'=>$game_array));

Please help me to solve this.. Thanks

Dibish
  • 9,133
  • 22
  • 64
  • 106
  • Doesn't `{$v.venue}` give you `venues`? – vee Jan 04 '14 at 04:17
  • thanks for quick reply, i have edited my question with more info, i tried $v.venue nothing displayed just '0: [' only – Dibish Jan 04 '14 at 04:24
  • If you pass this from json_decode() it may be an array of StdObject that Smarty cannot process. I write a small code piece to turn all StdObject to real array (still nested, by recursive function) before passing to Smarty and {$v.venue} should work. See if this helps! – Ken Cheung Jan 04 '14 at 04:29
  • I just tried $game_array = json_encode($listgame); $game_array = json_decode($game_array); then $v.venue. Now its display venue only. But i think something is wrong by doing this way. – Dibish Jan 04 '14 at 04:40

1 Answers1

2

Typically, in my MVC applications, I use Smarty to output HTML and completely bypass it to output JSON.

That is, I simply print the result of PHP's json_encode for outputting arrays as JSON. There's no reason at all to involve Smarty in this.

You'd struggle, anyway, to write a recursive Smarty template; it's not expressive enough for that. This isn't a failing of Smarty per se: it's not designed for such uses.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055