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.
GROUP_CONCAT should be your solution:
SELECT id, name,
GROUP_CONCAT( picture ORDER BY picture SEPARATOR '<br/'> ) as pictures
FROM your_table
GROUP BY id, name
it would require some playing with it to get your formating, however it could be the way
$my_parsed_data = array();
foreach($mydata as $data){
$my_parsed_data[$data->id]["id"] = $data->id;
$my_parsed_data[$data->id]["name"] = $data->name;
$my_parsed_data[$data->id]["photos"][] = $data->picture;
}
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:
class ArrayList{
private elements = array();
public function addElement(){
//some magic here =)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.