在 DOM 元素数组中取消设置空值

问题描述

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

解决方法

实际上,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]
    ];
}
}
,

不知道为什么第一个答案不会被接受。只需稍作调整即可使其正常工作。

在你的循环中

$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');
}

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

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