How to print a json in Smarty

泄露秘密 提交于 2019-12-05 10:23:52

You have 2 possible solutions.

First solution

in PHP you use:

$data = '[
    {
        "first_name": "jinu",
        "last_name": "mk",
        "loginid": "jinu@amt.in",
        "timezone": "5.5",
        "team_id": "c964ef415f157ddd99173f5b481ee1e3",
        "user_type": 1,
        "last_login_date": null
    },
    {
        "first_name": "avatar second",
        "last_name": "test",
        "loginid": "avatar2@gmail.com",
        "timezone": "5.5",
        "team_id": "ec40f5feda8643135bc20be44f897b03",
        "user_type": "3",
        "last_login_date": null
    },
    {
        "first_name": "avatar testing admin",
        "last_name": "amt 1",
        "loginid": "avatar@amt.in",
        "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": "jinu@amt.in",
        "timezone": "5.5",
        "team_id": "c964ef415f157ddd99173f5b481ee1e3",
        "user_type": 1,
        "last_login_date": null
    },
    {
        "first_name": "avatar second",
        "last_name": "test",
        "loginid": "avatar2@gmail.com",
        "timezone": "5.5",
        "team_id": "ec40f5feda8643135bc20be44f897b03",
        "user_type": "3",
        "last_login_date": null
    },
    {
        "first_name": "avatar testing admin",
        "last_name": "amt 1",
        "loginid": "avatar@amt.in",
        "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}

First of all you need to convert it to array then it will be much easier for you to loop through and print it

Say for you are getting your json in a variable named $response

// Convert to array
{$response|json_decode}

You will be getting an array now and you can loop through the array using {foreach}

After converting to array it will be easier for you to loop as foreach work for array and not for json output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!