json PHP -在对象数组中查找值

wnvonmuf  于 2023-06-25  发布在  PHP
关注(0)|答案(1)|浏览(154)

我正在使用一个JSON文件,它充当一个迷你数据库,它是这样布局的:

[
  {
    "id": "someIdentified",
    "name": "someName",
    "files" [
      {"url": "someUrl.ext","urlDescription": "Some Description"},
      {"url": "anotherUrl.ext", "urlDescrition": "Some other Description"}
    ]
  }
  {
    "id": "someIdentified",
    "name": "someName",
    "files" [
      {"url": "someUrl.ext","urlDescription": "Some Description"},
      {"url": "anotherUrl.ext", "urlDescrition": "Some other Description"}
    ]
  }
  {
    "id": "someIdentified",
    "name": "someName",
    "files" [
      {"url": "someUrl.ext","urlDescription": "Some Description"},
      {"url": "anotherUrl.ext", "urlDescrition": "Some other Description"}
    ]
  }
]

如果我想检查一个值是否存在于这个对象数组中的任何地方,例如“someName”是否存在或“someUrl.ext”是否存在,并让它返回true或false,我将如何做到?我似乎可以搜索一层深,但我不知道如何搜索更深...对PHP来说还是很新的,感谢所有的指导。

ohtdti5x

ohtdti5x1#

你必须进行递归搜索:

function searchValueRecursive($array, $value) {
        if (in_array($value, $array)) {
            return true;
        }

        foreach ($array as $element) {
            if (is_array($element) && $this->searchValueRecursive($element, $value)) {
                return true;
            }
        }

        return false;
    }

这是我做的测试:

$jsonString = <<<heredocstring
[
  {
    "id": "someIdentified",
    "name": "someName",
    "files": [
      {"url": "someUrl.ext","urlDescription": "Some Description"},
      {"url": "anotherUrl.ext", "urlDescrition": "Some other Description"}
    ]
  },
  {
    "id": "someIdentified",
    "name": "someName",
    "files": [
      {"url": "someUrl.ext","urlDescription": "Some Description"},
      {"url": "anotherUrl.ext", "urlDescrition": "Some other Description"}
    ]
  },
  {
    "id": "someIdentified",
    "name": "someName",
    "files": [
      {"url": "someUrl.ext","urlDescription": "Some Description find me"},
      {"url": "anotherUrl.ext", "urlDescrition": "Some other Description"}
    ]
  }
]
heredocstring;

$array = json_decode($jsonString, true); // 🟥 pass true to make it an assoc array

            $res = $this->searchValueRecursive($array, 'Some Description find me');

相关问题