遍历json,具有多个键值(某些相同的值)

时间:2019-03-13 15:27:13

标签: php json

我已经从数据库中导出了一些条目,该数据库为我提供了以下JSON:

[
  {
    "Artist_Title": "17 Hippies",
    "Gallery_Image_Filename": "17Hippies-2011-web.jpg"
  },
  {
    "Artist_Title": "17 Hippies",
    "Gallery_Image_Filename": "christo.jpg"
  },
  {
    "Artist_Title": "17 Hippies",
    "Gallery_Image_Filename": "kiki1.jpg"
  },
  {
    "Artist_Title": "17 Hippies",
    "Gallery_Image_Filename": "17-hippies.jpg"
  },
  {
    "Artist_Title": "17 Hippies",
    "Gallery_Image_Filename": "Photo1.jpg"
  },
  {
    "Artist_Title": "Ann Savoy Trio",
    "Gallery_Image_Filename": "Savoy-Trio-B&W-resize342x.jpg"
  },
  {
    "Artist_Title": "Baghdaddies",
    "Gallery_Image_Filename": "Baghdaddies-(Small).JPG"
  },
  {
    "Artist_Title": "Baghdaddies",
    "Gallery_Image_Filename": "Baghdaddies2.jpg"
  }
]

哪些图片与帖子相关。我已经导出了帖子标题(Artist_Title)和图像文件名(Gallery_Image_Filename)。

一个帖子可以有多个图库图像,这里的最终目标是执行一个foreach和var转储列表,例如

wget www.[domain].com/images/17Hippies-2011-web.jpg -O 17-hippies-gallery-1.jpg
wget www.[domain].com/images/christo.jpg -O 17-hippies-gallery-2.jpg
wget www.[domain].com/images/kiki1.jpg -O 17-hippies-gallery-3.jpg
wget www.[domain].com/images/17-hippies.jpg -O 17-hippies-gallery-4.jpg
wget www.[domain].com/images/Photo1.jpg -O 17-hippies-gallery-5.jpg
wget www.[domain].com/images/Savoy-Trio-B&W-resize342x.jpg -O ann-savoy-trio-1.jpg
wget www.[domain].com/images/Baghdaddies-(Small).JPG -O baghdaddies-gallery-1.jpg
wget www.[domain].com/images/Baghdaddies2.jpg -O 17-baghdaddies-gallery-2.jpg

所以从本质上讲,我正在创建图像URL的wget列表以及它们的新文件名。我使用帖子标题,对其进行了清理,并在-gallery- [number]后面加上了数字,该数字需要与找到的Artist_Title的数量相匹配。

我有这个foreach循环,我只需要修改它即可根据现在的帖子数量添加-[number]

foreach($gallery as $image) {
    echo 'wget https://www.accessallareas.info/images/' . $image->Gallery_Image_Filename . ' -O ' . sanitize_title($image->Article_Title) . '-gallery.jpg';
    echo '<br>';
}

这可以实现吗?

2 个答案:

答案 0 :(得分:1)

您可以为每个帖子保存一个计数器,然后在循环中检查一下。

尝试一下:

standard

注意:

  • 您的代码中有错字。 $pCounter = 0; // for Post counter $artistTitle = ''; foreach($gallery as $image) { if ($image->Artist_Title !== $artistTitle) { $pCounter = 0; } $counter++; echo 'wget https://www.accessallareas.info/images/' . $image->Gallery_Image_Filename . ' -O ' . $image->Artist_Title . '-gallery-'. $pCounter . '.jpg'; echo '<br>'; $artistTitle = $image->Artist_Title; } 应该是Article_Title
  • 您需要在代码顶部使用Artist_Title将JSON转换为对象数组。

答案 1 :(得分:0)

一切皆有可能。

$counter = 0;
$article_title = '';
foreach($gallery as $image) {
    if ($image->Article_Title !== $article_title) {
       $counter = 0;
    }
    $counter++;
    echo 'wget https://www.accessallareas.info/images/' . $image->Gallery_Image_Filename . ' -O ' . sanitize_title($image->Article_Title) . '-gallery-'. $counter .'.jpg';
    echo '<br>';
    $article_title = $image->Article_Title;
}