'inner array sorting in smarty
test1.php
<?php
include ("includes/application_top.inc.php");
$smarty->assign('user', array(
array('firstname' => 'john',
'lastname' => 'aaa',
'numbers'=>array(21,20,55,44)),
array('firstname' => 'jack',
'lastname' => 'zzz',
'numbers'=>array(23,21,76,34)),
array('firstname' => 'jill',
'lastname' => 'ddd',
'numbers'=>array(43,23,54,76)),
));
$smarty->display('test1.tpl');
?>
test1.tpl
<table>
{foreach item=item key=key from=$user|@sortby:"numbers"}
{$item.firstname} <br/>
{$item.lastname} <br/>
{$item.numbers} <br/>
{/foreach}
</table>
Question
I want result as sorted numbers. When i m performing sorting by firstname or lastname it is working fine. but only problem with array inside array.
Any idea how to do inner array sorting in smarty.
Solution 1:[1]
You should do sorting in PHP (or if you get data from database just proper order by in query).
Solution with sorting in PHP below:
PHP:
$arr1 = array(21,20,55,44);
$arr2 = array(23,21,76,34);
$arr3 = array(43,23,54,76);
sort($arr1);
sort($arr2);
sort($arr3);
$smarty->assign('user', array(
array('firstname' => 'john',
'lastname' => 'aaa',
'numbers'=> $arr1),
array('firstname' => 'jack',
'lastname' => 'zzz',
'numbers'=> $arr2),
array('firstname' => 'jill',
'lastname' => 'ddd',
'numbers'=>$arr3),
));
Smarty:
<table>
{foreach item=item key=key from=$user}
{$item.firstname} <br/>
{$item.lastname} <br/>
{foreach $item.numbers as $number}
{$number}
{/foreach}
<br/>
{/foreach}
</table>
In my opinion there is no point at all to do complex operation in template engine. Data should be prepared by PHP and Smarty should just display them.
Solution 2:[2]
You might want to do it like this:
<table>
{foreach item=item key=key from=$user}
{$item.firstname} <br/>
{$item.lastname} <br/>
{if $item.numbers|@sort eq 1}{/if}
{foreach $item.numbers as $number}
{$number},
{/foreach} <br/>
{/foreach}
</table>
To explain the if:
If you do {$item.numbers|@sort} it will echo 1 because that is the output of sort. But if you put it inside an if, the output is not shown on the page, but the function is runned.
The sortby thing is a plugin, which works different than you want to use it.
Solution 3:[3]
Agree with @Veda.
It will also work when loop is inside "if" correctly without echoing 1:
<table>
{foreach item=item key=key from=$user}
{$item.firstname} <br/>
{$item.lastname} <br/>
{if $item.numbers|@sort eq 1}
{foreach $item.numbers as $number}
{$number},
{/foreach}
{/if}
<br/>
{/foreach}
</table>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcin Nabiałek |
| Solution 2 | |
| Solution 3 | deWebLooper |
