【问题标题】:Search with fragment of a string in multidimensional array在多维数组中搜索字符串的片段
【发布时间】:2021-03-10 11:48:49
【问题描述】:

我有这样定义的 PHP 数组:

 {
  "data": [
    {
      "content": "Build your communication",
      "property": null,
      "name": "description"
    },
    {
      "content": "simplify it",
      "property": "og:title",
      "name": null
    },
    {
      "content": "unleash the effectiveness",
      "property": "og:description",
      "name": null
    },
    {
      "content": "https:\/\/uploads-ssl.webflow.com\/\/%%20SETTINGS.png",
      "property": "og:image",
      "name": null
    }
}

如何通过 property 键搜索并仅返回数组组,其中定义了值 og: 作为字符串一部分的属性字段。

    $crawler = new Crawler(file_get_contents($url));
    $items = $crawler->filter('meta');

    $metaData = [];
    foreach ($items as $item) {
        $itemCrawler = new Crawler($item);
        $content     = $itemCrawler->eq(0)->attr('content');
        $property    = $itemCrawler->eq(0)->attr('property');
        $name        = $itemCrawler->eq(0)->attr('name');

        $metaData = [
            'content' => $content,
            'property' => $property,
            'name' => $name,
        ];
    }
    
    return $metaData;;

试过了:

if(substr( $data['property'], 0, 3 ) === 'og:') {}

只返回第一个。

有人可以帮忙吗?

【问题讨论】:

  • 您发布的代码有语法错误,根本不应该运行。
  • 另外,$items 是什么?
  • 这是一种返回我的数据的方法。真是令人兴奋。我编辑了代码。 @El_Vanja
  • 抱歉,我不够精确 - $items 是您在问题开头显示的整个数组吗?还是只是data 索引下的子数组?语法错误怎么办?这些是否存在于您的实际代码中?
  • 没问题。 :) 它是数据索引下的子数组。目前,我没有任何语法错误。 @El_Vanja

标签: php arrays multidimensional-array


【解决方案1】:

这应该适合你。 $ret 将保存属性“property”包含“og:”的所有对象。

    $items = json_decode('{
  "data": [
    {
      "content": "Build your communication",
      "property": null,
      "name": "description"
    },
    {
      "content": "simplify it",
      "property": "og:title",
      "name": null
    },
    {
      "content": "unleash the effectiveness",
      "property": "og:description",
      "name": null
    },
    {
      "content": "https:\/\/uploads-ssl.webflow.com\/\/%%20SETTINGS.png",
      "property": "og:image",
      "name": null
    }
    ]}');

$ret = array_filter($items->data, function($item) {
    return strstr($item->property, "og:");
});

【讨论】:

    【解决方案2】:
    $data = [];
        foreach ($items["data"] as $item) {
            $content     = item['content'];
            $property    = item['property'];
            $name        = item['name'];
        $temp= [
            'content' => $content,
            'property' => $property,
            'name' => $name,
        ];
    array_push($data,$temp);
        }
    

    您在数组之前有一个“数据”关键字。试试这个

    【讨论】:

    • 除了没有解决 OP 代码的所有问题之外,这甚至没有尝试回答过滤元素的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    相关资源
    最近更新 更多