【问题标题】:Unset null values in array of DOM elements取消设置 DOM 元素数组中的空值
【发布时间】: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


【解决方案1】:

不确定为什么不接受第一个答案。只需进行一些调整即可使其正常工作。

在你的循环中

$itemCrawler = new Crawler($item);
$content = $itemCrawler->eq(0)->attr('content');
$property = $itemCrawler->eq(0)->attr('property');
if(!is_null($content) || !is_null($property)) {
    $metaData[] = compact('content', 'property');
}

或者如果你在得到$metaData数组后坚持使用array_filter

$filteredMetaData = array_filter($metaData, function($item) {
    return !is_null($item['content']) || !is_null($item['property']);
});

【讨论】:

    【解决方案2】:

    实际上,array_filter() 适用于空元素。

    即使元素值是空白的,如果键在,空白值也不会被移除。

    在代码中:

    $item 有两个键

    所以,添加显式条件来检查空白元素,请修改代码如下:

    $data = [];
    $items =$service->get('allData');
    foreach ($items as $item) {
        if (! empty($item['content']) && ! empty($item['property'])) {
        $data[] = [
            'content' => $item['content'],
            'property' => $item['property]
        ];
    }
    }
    

    【讨论】:

    • 非常感谢您的回答,但我应该更具体一些。这些是我试图访问的 DOM 元素。有问题。我更新了我的帖子。对此感到抱歉。 @瞳孔
    猜你喜欢
    • 2011-11-02
    • 1970-01-01
    • 2020-03-24
    • 2018-07-16
    • 2013-04-11
    • 2021-05-29
    • 2014-09-21
    • 2011-02-20
    • 2011-04-09
    相关资源
    最近更新 更多