Am getting a json from an api, how to print the json using Smarty.
Json format
[
{
"first_name": "jinu",
"last_name": "mk",
"loginid": "[email protected]",
"timezone": "5.5",
"team_id": "c964ef415f157ddd99173f5b481ee1e3",
"user_type": 1,
"last_login_date": null
},
{
"first_name": "avatar second",
"last_name": "test",
"loginid": "[email protected]",
"timezone": "5.5",
"team_id": "ec40f5feda8643135bc20be44f897b03",
"user_type": "3",
"last_login_date": null
},
{
"first_name": "avatar testing admin",
"last_name": "amt 1",
"loginid": "[email protected]",
"timezone": "5.5",
"team_id": "ec40f5feda8643135bc20be44f897b03",
"user_type": 1,
"last_login_date": null
}
]
I have tired the following foreach but its not printing anything.
{foreach from=$games item=foo}
<li>{$foo.first_name}</li>
{/foreach}
Please help me to solve this issue. Thanks
You have 2 possible solutions.
First solution
in PHP you use:
$data = '[
{
"first_name": "jinu",
"last_name": "mk",
"loginid": "[email protected]",
"timezone": "5.5",
"team_id": "c964ef415f157ddd99173f5b481ee1e3",
"user_type": 1,
"last_login_date": null
},
{
"first_name": "avatar second",
"last_name": "test",
"loginid": "[email protected]",
"timezone": "5.5",
"team_id": "ec40f5feda8643135bc20be44f897b03",
"user_type": "3",
"last_login_date": null
},
{
"first_name": "avatar testing admin",
"last_name": "amt 1",
"loginid": "[email protected]",
"timezone": "5.5",
"team_id": "ec40f5feda8643135bc20be44f897b03",
"user_type": 1,
"last_login_date": null
}
]';
$smarty->assign('games',$data);
In Smarty you use:
{foreach from=$games|json_decode item=foo}
<li>{$foo->first_name}</li>
{/foreach}
However I'm not sure in this case if json_decode
is run on $games
just once or on each invocation.
Second solution
In PHP you use:
$data = '[
{
"first_name": "jinu",
"last_name": "mk",
"loginid": "[email protected]",
"timezone": "5.5",
"team_id": "c964ef415f157ddd99173f5b481ee1e3",
"user_type": 1,
"last_login_date": null
},
{
"first_name": "avatar second",
"last_name": "test",
"loginid": "[email protected]",
"timezone": "5.5",
"team_id": "ec40f5feda8643135bc20be44f897b03",
"user_type": "3",
"last_login_date": null
},
{
"first_name": "avatar testing admin",
"last_name": "amt 1",
"loginid": "[email protected]",
"timezone": "5.5",
"team_id": "ec40f5feda8643135bc20be44f897b03",
"user_type": 1,
"last_login_date": null
}
]';
$smarty->assign('games',json_decode($data));
In Smarty file:
{foreach from=$games item=foo}
<li>{$foo->first_name}</li>
{/foreach}
I always recommend using second method, because if possible in Smarty you should avoid using any calculations and just display data.
Try the following:
{foreach from=$games item=foo}
{assign var=bar value=$foo|json_decode:1}
<li>{$bar.first_name}</li>
{/foreach}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With