【问题标题】:Nested Arrays Issue using Symfony 5/Twig "Array to string conversion"使用 Symfony 5/Twig“数组到字符串转换”的嵌套数组问题
【发布时间】:2023-03-26 21:09:01
【问题描述】:

我尝试使用以下方法显示一个简单的a 链接:

Symfony\Component\DomCrawler\Crawler

Symfony\Component\Panther\Client

我需要提取h2 > a 并将它们显示到树枝上

在我的班级控制器中:

$linkMetaInfo = [];
$crawler->filter('h2 a')->each(function (Crawler $node) use (&$linkMetaInfo) {

        $linkMetaInfo['link'][] = $node->attr('href');
        $linkMetaInfo['text'][] = $node->text();

    });
 return $linkMetaInfo;

路由控制器:

        return $this->render('home/display-meta.html.twig', [

        'linkMetaInfos' => $linkMetaInfos

        ]);

转储:

array:2 [▼
  "linkMetaInfos" => array:2 [▼
    "link" => array:27 [▼
      0 => "https://bootstrapmade.com/flexstart-bootstrap-startup-template/"
      1 => "https://bootstrapmade.com/bootslander-free-bootstrap-landing-page-template/"
      2 => "https://bootstrapmade.com/arsha-free-bootstrap-html-template-corporate/"
      3 => "https://bootstrapmade.com/free-bootstrap-template-corporate-moderna/"
      4 => "https://bootstrapmade.com/free-html-bootstrap-template-my-resume/"
      5 => "https://bootstrapmade.com/iportfolio-bootstrap-portfolio-websites-template/"
      ]
    "text" => array:27 [▼
      0 => "FlexStart"
      1 => "Bootslander"
      2 => "Arsha"
      3 => "Moderna"
      4 => "MyResume"
      5 => "iPortfolio]
  ]
  "app" => Symfony\Bridge\Twig\AppVariable {#178 ▶}
]

在我的树枝视图中:

{% for linkMetaInfo  in linkMetaInfos %}
    
    <a href="{{ linkMetaInfos.link }}">{{ linkMetaInfos.text }}</a>

    {% endfor %}

如果我这样做:

{{ dump(linkMetaInfos.link) }}

{{ dump(linkMetaInfos.link) }}

一切正常

但是当我尝试时:

<a href="{{ linkMetaInfos.link }}">{{ linkMetaInfos.text }}</a>

我收到了这条消息:

在渲染模板期间抛出异常(“注意:数组到字符串的转换”)。

如果我尝试:

{{ dump(linkMetaInfo.text) }}

{{ dump(linkMetaInfo.link) }}

我收到了这条消息:

键为“0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 的数组的键“链接” , 18, 19, 20, 21, 22, 23, 24, 25, 26" 不存在。

有什么想法吗? 提前谢谢

【问题讨论】:

  • 如果您的解决方案与其他人提出的不同,请将其添加到答案部分而不是问题中

标签: php arrays symfony twig


【解决方案1】:

你说它是一个嵌套数组,所以你必须在嵌套数组中循环,不是吗?

在下一个示例中,您将在链接中循环,并与文本进行协调,但要注意长度相同...

{% for linkMetaInfo  in linkMetaInfos.link %}
     <a href="{{ linkMetaInfo }}">{{ linkMetaInfos.text[loop.index0] }}</a>
{% endfor %}

【讨论】:

  • 谢谢帕特里克!!它完美地工作嵌套数组?好问题我的目标是将这两个数组包含到一个名为 h2Content 的数组中:[linkMetaInfos -> [h2Content ->[link] ->[text] ] ]
猜你喜欢
  • 2015-12-14
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 2014-04-05
  • 2014-03-16
相关资源
最近更新 更多