我有一个包含以下内容的文件:

[
  {
    "photographer": "chrysti",
    "picture": "ChristyHydeck_1.jpg",
    "themes": [
      "pets"
    ]
  },
  {
    "photographer": "chrysti",
    "picture": "ChristyHydeck_2.jpg",
    "themes": [
      "everyday",
      "pets"
    ]
  },
  {
    "photographer": "chrysti",
    "picture": "ChristyHydeck_3.jpg",
    "themes": [
      "outdoors"
    ]
  },
  {
    "photographer": "jeremy",
    "picture": "JeremyVeach_41.jpg",
    "themes": [
      "everyday",
      "pets"
    ]
  }
]

我想根据一些过滤器(传递给函数的参数)搜索项目,这就是我所拥有的:
static function filterImage($photographers = null, $themes = null)
{
    $images = array();
    $string = file_get_contents( "assets/main/images.json" );

    $jsonIterator = new RecursiveIteratorIterator(
        new RecursiveArrayIterator( json_decode( $string, true ) ),
        RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($jsonIterator as $key => $val) {
        if (is_array( $val )) {
            for ($i = 0; $i < count($val); $i++) {
                if (in_array($val[$i], $photographers) || in_array($val[$i], $themes)) {
                    // code goes here
                }
            }
        } else {
            echo "$key => $val\n";
        }
    }

    return $images;
}

我一直试图返回一个数组,其中包含条件匹配的currentimages.json值以picture作为chrysti参数,函数的输出应该如下:
$images = ["ChristyHydeck_1.jpg", "ChristyHydeck_2.jpg", "ChristyHydeck_2.jpg"];

现在让我们执行与参数相同的传递photographer,在这种情况下,输出应该是:
$images = ["ChristyHydeck_2.jpg", "JeremyVeach_41.jpg"];

条件匹配时如何获取everyday值有人能给我一些完成这件事的建议吗?

最佳答案

尝试下面的代码

$images = array();
$string = file_get_contents( "assets/main/images.json" );
$json = json_decode($string, true);
foreach ($json as $key => $val) {
     if(in_array($val['photographer'],$photographers)){
          $images[] = $val['picture'];
     }
    foreach ($val['themes'] as $key1 => $val1){
        if(in_array($val1,$themes)){
             $images[] = $val['picture'];
        }
    }
}

希望这对你有帮助。

关于php - 获取按主题或摄影师过滤的图片数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29574700/

10-10 20:59