ProgrammingPHP Arrays question helpPosted:

Status: Offline
Joined: Mar 01, 20117 Year Member
Posts: 356
Reputation Power: 24
I am new to PHP and I am trying to solve this array problem but I'm stuck on it and I was wondering if anyone could help me out. I started out by doing a random number function on a multidimensional array but it didn't work the way the question asks. I was wondering if you could help me out?

This is the question....

Janet decides to celebrate Yorkshire Day (1st August) by randomly discounting the price of one of three randomly selected different beers by between 10 and 25 percent on an hourly basis between the hours of 5 to 10 PM. The beers and undiscounted prices are:

1. Centurion's Ghost Ale (York Brewery) £3.30
2. Stallion (Hambleton Ales) £3.10
3. Ram Tam (Timothy Taylor Brewery) £2.80

The problem is to randomly select a beer and its randomly selected discounted price on an hourly basis throughout the evening.
For example:
From 5 to 6 PM we are selling Ram Tam for £2.33 From 6 to 7 PM we are selling Stallion for £2.69
From 10 to 11 PM we are selling Ghost Ale for £2.86

Your solution should outputs the discounted price and beer per hour throughout the period.
#2. Posted:
Status: Offline
Joined: Aug 14, 20135 Year Member
Posts: 72
Reputation Power: 10
In oder for someone to help you we would need to see the code. Post the part of the code where you think its going wrong
#3. Posted:
Status: Offline
Joined: Feb 25, 20162 Year Member
Posts: 19
Reputation Power: 13
tried to make this as noob as possible so you can wrap your head around it and get an idea on how to accomplish things.

The proper way to do this would be making a function and using recursion to avoid colliding sales on the beers, and if you want it to do that then you should take the time to learn what recursion is and how to leverage it.

Here you go.


$beers_retail = [
      "name" => "Centurions",
      "price" => 3.30
        "name" => "Stallion",
        "price" => 3.10
        "name" => "Ram Tam",
        "price" => 2.80

$discount_range = [10, 15];

$hours_discount = 3;

$hourly_discount_stack = [];

for ($i = 0; $i < $hours_discount; $i++) {
    $discounted = $beers_retail[mt_rand(0, count($beers_retail) - 1)];
    array_push($hourly_discount_stack, [
        "name" => $discounted["name"],
        "price" => round($discounted["price"] * (sprintf(
            '.%d', (100 - mt_rand($discount_range[0], $discount_range[1]
        )))), 2),
        "hour_start" => date('h:i A', time() + ($i * 3600)),
        "hour_end" => date('h:i A', time() + ($i * 3600) + 3600)

Users browsing this topic: None
Jump to: