Search with fragment of a string in multidimensional array

I have PHP array defined like this:

 {
  "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
    }
}

How can I search trough property keys and return just array groups where property field with values og: as a part of the string is defined.

    $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;;

Tried with :

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

Returns just first one.

Can someone help?

Answer

This should work for you. $ret will hold all objects where the property “property” contains “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:");
});

Leave a Reply

Your email address will not be published. Required fields are marked *