Reputation: 147
How can i use array_push from PHP functions in Smarty Template.
I tried this
{assign var='out' value=array()}
{foreach $data['data'] as $dataInfo}
{$out|@array_push {$dataInfo['a']}:{$dataInfo['b']}}
{/foreach}
{$out|var_dump}
Upvotes: 2
Views: 2034
Reputation: 111829
You haven't explained what result you want to achieve and in fact you should rather do such things in controller/model than in view.
However if in PHP you have:
$smarty->assign(
'data',
array(
'data' => array(
array('a' => 'one', 'b' => 'two'),
array('a' => 'three', 'b' => 'four')
)
)
);
And in Smarty file you have:
{assign var='out' value=array()}
{foreach $data['data'] as $dataInfo}
{append var='out' value=$dataInfo['a']}
{append var='out' value=$dataInfo['b']}
{/foreach}
{$out|var_dump}
Output will be:
array(4) { [0]=> string(3) "one" [1]=> string(3) "two" [2]=> string(5) "three" [3]=> string(4) "four" }
as expected.
array_push
in this case is not the best solution because it will also display number of elements, so using:
{assign var='out' value=array()}
{foreach $data['data'] as $dataInfo}
{$out|array_push:$dataInfo['a']}<br />
{$out|array_push:$dataInfo['b']}<br />
{/foreach}
{$out|var_dump}
you would also get numbers displayed:
1
2
3
4
array(4) { [0]=> string(3) "one" [1]=> string(3) "two" [2]=> string(5) "three" [3]=> string(4) "four" }
EDITED ANSWER ACCORDING TO COMMENT
I want to display like this: a:b, c:d where this elements are| $array[0] = Array('aa' => 'a', 'bb' => 'b') $array[1] = Array('cc'=>'c', 'dd'=>'d');
If in PHP you have:
$array = array();
$array[0] = Array('aa' => 'a', 'bb' => 'b');
$array[1] = Array('cc'=>'c', 'dd'=>'d');
$smarty->assign(
'data', $array
);
In Smarty you should use:
{foreach $data as $dataInfo}
{$dataInfo|implode:':'}{if not $dataInfo@last}, {/if}
{/foreach}
Output will be:
a:b, c:d
But it's not connected to the question in anyway where you asked about using PHP function array_push
in Smarty template
Upvotes: 8