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 trial
Melfred Pretorius
3,674 PointsDisplaying five random $product while maintaining key => value?
I am trying to include a "You might also be interested in:" section on my site. I am able to shuffle and display the correct number of products that I want. However, I am losing the $product_id and therefore my links are broken.
The code I have tried without success:
<div class="row"> <div class="span12"> <ul id="tiles"> <?php
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[] = $list[$key];
}
return $random;
}
$get_list_view = "";
shuffle_assoc($products);
$total_products = count($products);
$position = 0;
foreach($products as $product_id => $product) {
$position = $position + 1;
if ($position < 6) {
$get_list_view = get_list_view_html($product_id, $product) . $get_list_view;
} else {}
}
echo "$get_list_view";
?>
</ul>
</div>
</div>
Any help will be appreciated.
1 Answer
Randy Hoyt
Treehouse Guest TeacherHave you watched the videos in the Refactoring my Codebase course? [http://teamtreehouse.com/library/programming/enhancing-a-simple-php-application/refactoring-the-codebase] The first three deal with this issue. We use automated duplication to put the key inside the array as an attribute, as well, to avoid this exact problem.