【发布时间】:2021-03-08 09:36:49
【问题描述】:
我在 php 中迭代槽数组,结果如下: 它是一个在 DOM Crawler 库中包含 DOM 元素的数组。
{
"data": [
{
"content": null,
"property": null
},
{
"content": "Build your communication strategy and unleash the effectiveness and efficiency of your storytelling",
"property": null
}
}
...
在我的代码中:
$crawler = new Crawler(file_get_contents($url));
$items =$crawler->filter('meta');
$metaData = [];
foreach ($items as $item) {
$itemCrawler = new Crawler($item);
$metaData[] = [
'content' => $itemCrawler->eq(0)->attr('content'),
'property' => $itemCrawler->eq(0)->attr('property')
];
}
我试图完成的是删除两个字段都是 NULL 的行,就像第一个一样(如果有一个字段,比如第二个而不是跳过)。
尝试使用 array_filter() 但没有成功。
return array_filter($metaData, 'strlen');
【问题讨论】:
-
为什么要在过滤后删除它们——只是不首先将它们添加到数组中?
if( ! ( is_null($item['value-1']) && is_null($item['value-2']) ) ) { $data[] = …; } -
array_filter将不起作用,因为您有一个数组数组,并且每个子数组都有两个索引,因此不会评估为假值,因为它不被认为是空的(尽管内容为空) .但是,当您可以在构建数组时应用逻辑时,为什么还要过滤呢?在您的foreach中添加一个if,如果两个值都不是null,它只会向$data添加一个新元素。
标签: php symfony multidimensional-array array-filter domcrawler