How to search JSON in PHP?

Hi
How can I search JSON variable than return the exact value that matches the search?
I’m making a email client and email services have different names for there inbox but usually always contains “inbox”
Hers how far I got but it does not work correctly:

  $folders = $imap->getFolders();

      function strposa($haystack, $needle, $offset=0) {
        if(!is_array($needle)) $needle = array($needle);
        foreach($needle as $query) {
          if(strpos($haystack, $query, $offset) !== false) return true; // stop on first true result
        }
        return false;
      }
        $array  = json_encode($folders,  JSON_PRETTY_PRINT);

      var_dump(strposa($params['mailbox'], $array));

So $array contains in this instance:

{
    "Calendar": [],
    "Calendar\/Birthdays": [],
    "Calendar\/United Kingdom holidays": [],
    "Contacts": [],
    "Conversation History": [],
    "Deleted Items": [],
    "Drafts": [],
    "INBOX": [],
    "Journal": [],
    "Junk Email": [],
    "Notes": [],
    "Outbox": [],
    "Sent Items": [],
    "Tasks": []
} 

and $params['mailbox'] contains “INBOX” but the function reruns bool(false)
If I change $arrary to $array = array("Junk","Sent","INBOX"); it finds “INBOX”.
Any ideas?
Thanks in advance.

The first rule of JSON club:

#You never ever lay your hands on the encoded value.

So if you want to search for a key, then get array keys and then search in them.

$keys = array_keys($folders);
$needle = array("INBOX");
var_dump((bool)array_intersect($keys, $needle));

without that silly encoding /string manipulation

1 Like

PHP Notice: Array to string conversion

Ah yes it should be $keys. A silly typo. Fixed now

thanks it works:

$keys = array_keys($folders);
$needle = array($params['mailbox']);
var_dump((bool)array_intersect($keys, $needle));

Any way to make it not case sensitive ?

array_uintersect($keys, $needle, "strcasecmp")
1 Like

Works!

It wont find "Sent Items" cuz of the space when I serched for "sent".
Anyway to make it serch with the space?
Thanks.

Sure, provide a custom function to array_uintersect() that contains the search logic.

So there’s no built in function like strcasecmp?

No.

That’s due to the ‘unnatural’ return value requirement for these type of functions.

This worked for me in the end:

$searchword = $params['mailbox'];
$matches = array();
foreach($folders as $k=>$v) {
  //print_r($k);
    if(preg_match("/\b$searchword\b/i", $k)) {
        $matches[$k] = $k;
    }
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.