合并对象数组中除一个值之外的重复项... php/mysql
这是我的数据的简化版本。这是使用 JOIN 进行查询的结果,并生成如下数据:
id name picture
1 Foo picture_001.jpg
1 Foo picture_002.jpg
2 Bar another_image.jpg
3 Baz some_picture_001.jpg
3 Baz some_picture_002.jpg
输出是一个对象数组,如下所示(最小化以仅显示 ID 1 的数据):
print_r($my_data); // produces:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Foo
[picture] = picture_001.jpg
)
[1] => stdClass Object
(
[id] => 1
[name] => Foo
[picture] = picture_002.jpg
)
)
该数组可能包含多个具有不同 ID 的对象,名字和图片。
我试图循环遍历每个对象并输出数据。我这样做是这样的:
foreach($object as $item)
{
echo $item->id;
}
这确实有效,但正如预期的那样,由于连接而产生重复的数据。
我已经寻找解决方案,但我不知道如何防止这种重复的发生。
在上面的数据转储中,我希望输出为:
ID 1
Name: Foo
Pictures in Foo:
picture_001.jpg
picture_002.jpg
ID 2
Name:Bar
Pictures in Bar
another_image.jpg
因此,如果一个项目有多张图片,则会将其分组在一起。
我可以提供 SQL,并可能更改数据的输出方式,但我想首先了解其背后的方法,以及如何进行此操作。
提前致谢。
Here is a simplified version of my data. This is the result of a query using a JOIN and produces data like this:
id name picture
1 Foo picture_001.jpg
1 Foo picture_002.jpg
2 Bar another_image.jpg
3 Baz some_picture_001.jpg
3 Baz some_picture_002.jpg
The output is an array of objects, which looks like this (minimised to just show ID 1's data):
print_r($my_data); // produces:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Foo
[picture] = picture_001.jpg
)
[1] => stdClass Object
(
[id] => 1
[name] => Foo
[picture] = picture_002.jpg
)
)
This array might contain several more objects, with different ID's, names and pictures.
I am trying to cycle through each object and output the data. This I am doing like so:
foreach($object as $item)
{
echo $item->id;
}
This does work, but as expected, produces duplicated data as a result of the join.
I have searched for a solution but I can not get my head around how to prevent this duplication from occuring.
In my data dump above, I would want the output to be:
ID 1
Name: Foo
Pictures in Foo:
picture_001.jpg
picture_002.jpg
ID 2
Name:Bar
Pictures in Bar
another_image.jpg
So if an item has multiple pictures, it is grouped together.
I can provide SQL, and possibly change how the data is output, but I would like to see the methodology behind this first, and how to go about this.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个解决方案将为您提供一个简单的信息数组,您想要的格式...如果您想要一个对象数组,那么您必须创建一个模拟此代码的类,例如:
this solution will give you a simple array of the info the format you want... if you want an array of objects instead then you'll have to create a class that emulates this code, something like:
GROUP_CONCAT 应该是您的解决方案:
需要一些操作才能获得格式,但这可能是这样
GROUP_CONCAT should be your solution:
it would require some playing with it to get your formating, however it could be the way