Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSuzanne Cranen
7,497 PointsRelated items php array
Hi,
For my portfolio website I would like to show on the detailpage of an item, other items that are related to that one. On my portfolio there will be 3 categories: films, animations and pictures. So when the detailpage of a film is shown, I would like to show 3 other random related films as well...
How can I do that?
My array items look like this and I want to select related items by using the index "category".
$portfolio[] = array(
"title" => "De Ontmoeting",
"sort" => "Short Film",
"slide" => "img/slider2.png",
"genre" => "comedy",
"category" => "Film",
"function" => array("producer", "audio", "webdesigner")
);
3 Answers
Joel Bardsley
31,249 PointsI've spent a bit of time over lunch on this workspace using functions and array methods if you want to play around with it. Array methods are something I need to practice further with so if anyone has any suggestions for improvements or general refactoring, I'd greatly appreciate it.
Simon Coates
28,694 Pointsok, the first suggestion is likely to be use a database. However, you can use array methods and randomisation of keysets generated on a subset of array entries. I've demoed this (probably badly):
<?php
$current = "De Ontmoeting";
$category = "Film";
$portfolio[] = array( "title" => "De Ontmoeting", "category" => "Film");
$portfolio[] = array( "title" => "De Ontmoeting2", "category" => "Film");
$portfolio[] = array( "title" => "De Ontmoeting3", "category" => "Film");
$portfolio[] = array( "title" => "De Ontmoeting4", "category" => "Film");
$portfolio[] = array( "title" => "De Onting4", "category" => "Fsilm");
$portfolio[] = array( "title" => "De Ontmoeting5", "category" => "Film");
$catKey = [];
foreach($portfolio as $key=>$item){
if($item["title"]!= $current && $item["category"]== $category){
$catKey[] = $key;
echo "$current {$item['title']}\n";
}
}
$random = 2;
foreach(array_rand ( $catKey, $random) as $item){
echo $portfolio[ $catKey[$item]]['title']."\n";
}
It goes looking in the array for films that aren't the current one to build a keyset to be used for randomisation. You might be able to use array methods to come up with a less clumsy method.
Suzanne Cranen
7,497 PointsThank you guys :D It's working now!