I am working on a PHP project and I am have multidimensional array and I am trying to loop through the array in Smarty to display it.
I am creating the following code in PHP
if (count($routeFields) > 1)
{
$savedRoutes[$count] = new RouteDetails();
$savedRoutes[$count]->destination = $routeFields[DESTINATION];
$savedRoutes[$count]->gateway = $routeFields[GATEWAY];
$savedRoutes[$count]->genmask = $routeFields[GENMASK];
$savedRoutes[$count]->flags = $routeFields[FLAGS];
$savedRoutes[$count]->metric = $routeFields[METRIC];
$savedRoutes[$count]->ref = $routeFields[REF];
$savedRoutes[$count]->use = $routeFields[USEF];
$savedRoutes[$count]->iface = $routeFields[IFACE];
$count++;
}
return $savedRoutes;
class RouteDetails
{
public $destination;
public $gateway;
public $genmask;
public $flags;
public $metric;
public $ref;
public $use;
public $iface;
}
Below is how I am calling my function and giving it to Smarty
$smarty = new Smarty();
$smarty->setTemplateDir("templates");
$routeManagement = new RouteManagement();
$result = $routeManagement->getRoutes();
$smarty->assign("routes", $result);
$smarty->display('routes.tpl');
Below is my Smarty template
<table>
<tr>
<td>Destination</td>
<td>Gateway</td>
<td>Genmask</td>
<td>Flags</td>
<td>Metric</td>
<td>Ref</td>
<td>Use</td>
<td>Iface</td>
</tr>
{foreach from=$routes key=key item=item}
<tr>
<td>{$item.destination}</td>
</tr>
{/foreach}
</table>
I get the following error displayed:
Fatal error: Cannot use object of type RouteDetails as array in /var/www/html/RouteManagement/templates_c/06dfeb8eb18eac12fde3a6f643d7f25678e14aaf.file.routes.tpl.php on line 46
Below is an output of $result
Array
(
[0] => RouteDetails Object
(
[destination] => 192.168.1.0
[gateway] => *
[genmask] => 255.255.255.0
[flags] => U
[metric] => 0
[ref] => 0
[use] => 0
[iface] => eth0
)
)
Ah, I get it. $item is an object, not an array. the smarty $item.destination means you are trying to access it like $item['destination']. Try $item->destination