【问题标题】:Two dimensional array with Smarty - fatal error cannot use object of type带有 Smarty 的二维数组 - 致命错误不能使用类型的对象
【发布时间】:2014-11-23 01:48:02
【问题描述】:

我正在开发一个 PHP 项目,我有一个多维数组,我试图在 Smarty 中循环遍历数组以显示它。

我正在 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;
    }

以下是我如何调用我的函数并将其提供给 Smarty

$smarty = new Smarty();
                    $smarty->setTemplateDir("templates");

                    $routeManagement = new RouteManagement();
                    $result = $routeManagement->getRoutes();

                    $smarty->assign("routes", $result);

                    $smarty->display('routes.tpl');

下面是我的 Smarty 模板

<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>

显示以下错误:

致命错误:无法使用 RouteDetails 类型的对象作为数组 /var/www/html/RouteManagement/templates_c/06dfeb8eb18eac12fde3a6f643d7f25678e14aaf.file.routes.tpl.php 第 46 行

下面是 $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
        )
)

【问题讨论】:

  • 在将其分配给 smarty 之前尝试 print_r($result) 以确保该值是您所期望的。是否可能 routeFields 也是一个二维数组?您正在检查大小,就好像您期望多个数组一样,但您不会在每个数组中进行迭代。
  • @DAB 我已经完成了 print_r,将其添加到我的问题中,RouteDetails 不是多维的

标签: php arrays smarty


【解决方案1】:

啊,我明白了。 $item 是一个对象,而不是一个数组。 smarty $item.destination 意味着您正尝试像 $item['destination'] 一样访问它。试试 $item->destination

【讨论】:

  • 谢谢 我以为我试过了,但显然没有。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多