• 0

Looping through values to perform a calculation


Go to solution Solved by spacer,

Question

game_over

I have developed a web app that logs children attending a club using PHP and have been asked to add a finance module that calculates how much each member owes based on days they are attending... off the top of my head the only way to do it is to create a query that pulls children based on certain criteria and then loop through the fields to decide whether to charge them.

 

Here is some sample data:

 

Screen%20Shot%202015-02-27%20at%2013.28.

 

The important part for now is the days they are attending, if a child is attending monday then the cell holds 1 integer, i the child is not attending on a specified day then it holds a zero.

 

Here is my god awful code that doesn't even work:

    $query_bc_income_week = Booking::ofClub('Breakfast Club')->term()->get(); // query returns children based on Breakfast Club and which term, the important thing to note is that this works and returns rows.
    $days = Config::get('config.dates'); // array

    $amount = 0;
    foreach($query_bc_income_week as $child)
    {
      foreach($days as $day)
      {
        $day = strtolower($day);
        if($child->$day == 1)
        {
          $bc_income_week = ($amount + 0.50);
        }
      }
      echo $bc_income_week;

So after the query i put the days (mon-fri) into an array and then set the $amount to 0.

Then i use a foreach to grab each child which can now be accessed via $child->column (i.e. $child->monday)

I have a nested foreach that loops through each day and assigned it to the column.

 

In English: the for each selects the child and then the second loop selects the day, if the $child->day column holds 1 then add 0.50 to the amount, after it has looped through 5 days(from the array) it will go back to the next child and do the same for the days here, each time incrementing by 0.50 every time it finds a 1. 

 

$bc_income_week returns: 0.50.50.50.50.50.50.50.50.50.50.50.50.50.50.50.50.50.5

 

Sorry for my poor explanation, hope it makes sense, surely there must be a better way to achieve this? It is possible my table structure is the real problem but couldn't think of a easier way to access the data.

 

This is just one calculation that I need to perform, I also need to get the income based on week, term and for both clubs, that is a lot of queries and loops.

 

Any ideas how I can do this better?

Link to post
Share on other sites

3 answers to this question

Recommended Posts

  • 0
spacer

In the code you posted, you're never incrementing $amount. You're adding to it, but you're never assigning the result of the addition to $amount so it's never updated.

 

So to fix your code, you should probably initialize $amount inside the child loop, so that every child starts at 0, then just you just need to add the assignment statement in there.

 

Also, I'm not sure what the difference is between $amount and $bc_income_week. I am making the assumption that $amount is the individual child cost, and $bc_income_week is the total cost for all children...

$bc_income_week = 0;
 
foreach($query_bc_income_week as $child)
{
    $amount = 0;

    foreach($days as $day)
    {
        $day = strtolower($day);

        if ($child->$day == 1)
        {
            $amount += 0.50;
        }
    }
 
    $bc_income_week += $amount;
    echo "Child's cost: " + $amount;
}
 
echo "Total cost for all children: " + $bc_income_week;

I'm extremely rusty with PHP, so I apologize if the syntax is wrong.

 

As for the data model question, I don't think anyone would be able to answer that without more knowledge of the problem scope. Designing good data models is an entire field of study/focus for some developers/architects, so it's not a trivial problem to solve.

Link to post
Share on other sites
  • 0
game_over

In the code you posted, you're never incrementing $amount. You're adding to it, but you're never assigning the result of the addition to $amount so it's never updated.

 

So to fix your code, you should probably initialize $amount inside the child loop, so that every child starts at 0, then just you just need to add the assignment statement in there.

 

Also, I'm not sure what the difference is between $amount and $bc_income_week. I am making the assumption that $amount is the individual child cost, and $bc_income_week is the total cost for all children...

$bc_income_week = 0;
 
foreach($query_bc_income_week as $child)
{
    $amount = 0;

    foreach($days as $day)
    {
        $day = strtolower($day);

        if ($child->$day == 1)
        {
            $amount += 0.50;
        }
    }
 
    $bc_income_week += $amount;
    echo "Child's cost: " + $amount;
}
 
echo "Total cost for all children: " + $bc_income_week;

I'm extremely rusty with PHP, so I apologize if the syntax is wrong.

 

As for the data model question, I don't think anyone would be able to answer that without more knowledge of the problem scope. Designing good data models is an entire field of study/focus for some developers/architects, so it's not a trivial problem to solve.

 

This works perfect thanks, I know it's not the best way to do it but I can throw it in a function to avoid repeating it.

 

thank you :)

Link to post
Share on other sites
  • 0
spacer

Glad I could help! Good luck with the rest of your project.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By News Staff
      Save 94% off the cost of this Essential PHP Coding Bundle
      by Steven Parker

      Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where for only a limited time, you can save 94% off this Essential PHP Coding Bundle. Get started in web development by learning the fundamentals of PHP coding and practicing object-oriented programming.



      This bundle consists of the following courses:

      Fundamentals of PHP Training Course
      Learn the Basic Programming Concepts in the Most Popularly Used Server-Side Programming Language PHP Development with the Laravel Framework Training Course
      Develop Homepages, Create Accounts & Activate Emails Using the Open-Source Laravel PHP Framework PHP Object Oriented Programming: Build a Login System Training Course
      Create an R/L System Using PHP & OOP Together Python Object Oriented Programming Fundamentals Training Course
      Create Advanced & Easily Maintainable Python Applications with Object-Oriented Programming Good to know
      Length of time users can access this course: 1 Year Certification of completion included Redemption deadline: redeem your code within 30 days of purchase For specifications and instructor info please click here.

      Here's the deal:
      This Essential PHP Coding Bundle normally costs* $516, but it can be yours for just $29.99 for a limited time, that's a saving of $486.01 (94%).

      >> Get this deal, or learn more about it here <<
      See all Online Courses on offer. This is a time-limited offer that ends soon.
      Get $1 credit for every $25 spent · Give $10, Get $10 · 10% off for first-time buyers.

      Not for you?
      If this offer doesn't interest you, why not check out the following offers:

      The Win Your Dream 2020 Tesla Model 3 Giveaway
      20% off Ivacy VPN subscription with coupon code IVACY20 NordVPN subscription at up to 68% off for a 2 year plan Private Internet Access VPN subscription at up to 71% off Unlocator VPN or SmartDNS unblock Geoblock with 7-day free trial Disable Sponsored posts · Other recent deals · Preferred partner software

      Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.

    • By News Staff
      Get this Interactive Learn to Code Bundle at 73% off for just $29.99
      by Steven Parker

      Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where you can save 73% off the Interactive Learn to Code Bundle. Start writing codes and programs from scratch with 9 interactive courses on SQL, JavaScript, PHP, jQuery, BootStrap, and more.



      This deal consists of the following courses:

      An Interactive SQL Tutorial for Beginners: Introduction to SQL
      Getting Started with SQL Doesn't Have to Be Hard An Interactive JavaScript Course for Beginners
      Learn JavaScript Interactively with a One-of-a-Kind JS Online Course Interactive jQuery Tutorial: Learn jQuery Step-by-Step
      Take an Interactive jQuery Training Course for Beginners to Quickly Master jQuery Events, Effects & More Learn PHP Online: PHP Basics Explained in an Interactive & Fun Manner
      An Interactive Tutorial for Beginners Who Want to Master PHP Basics in a Non-Boring Way The Complete Solidity Smart Contract Guide
      Master Solidity Programming Through Hands-On Experience Master Python Fundamentals the Fun Way: An Interactive Python Tutorial
      A Python Training Course for Absolute Beginners Who Wants to Master the Language Without Getting Bored A Responsive Web Design Course: Find Out How to Create a Responsive Website
      Make a Website Mobile-Friendly with a Step by Step, Responsive Web Design Tutorial Bootstrap Tutorial: Learn to Create Dynamic Websites in a Pinch
      Find Out How to Use Bootstrap the Fun Way by Using an Interactive Course An Interactive Java Tutorial: Learn by Practice!
      Learn Java From Scratch by Combining Theory with Hands-On Coding Experience Good to know
      Length of time users can access this course: lifetime Certification of completion included Redemption deadline: redeem your code within 30 days of purchase For a full description, specs, and instructor info, click here.

      Here's the deal:
      This Interactive Learn to Code Bundle normally costs* $112, but you can pick it up for just $29.99 for a limited time - that represents a saving of $82.01 (73%) off.

      >> Get this deal, or learn more about it <<
      See all discounted Online Courses. This is a time-limited offer.


      Get $1 credit for every $25 spent · Give $10, Get $10 · 10% off for first-time buyers.

      Not for you?
      If this offer doesn't interest you, why not check out the following offers:

      The Win Your Dream 2020 Tesla Model 3 Giveaway
      The Nintendo Gaming Bundle Giveaway 20% off Ivacy VPN subscription with coupon code IVACY20 NordVPN subscription at up to 68% off for a 2 year plan Private Internet Access VPN subscription at up to 71% off Unlocator VPN or SmartDNS unblock Geoblock with 7-day free trial Disable Sponsored posts · Other recent deals · Preferred partner software

      Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.

      running costs.

    • By News Staff
      Save 73% off the Interactive Learn to Code Bundle - now just $29.99
      by Steven Parker

      Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where you can save 73% off the Interactive Learn to Code Bundle. Start writing codes and programs from scratch with 9 interactive courses on SQL, JavaScript, PHP, jQuery, BootStrap, and more.



      This deal consists of the following courses:

      An Interactive SQL Tutorial for Beginners: Introduction to SQL
      Getting Started with SQL Doesn't Have to Be Hard An Interactive JavaScript Course for Beginners
      Learn JavaScript Interactively with a One-of-a-Kind JS Online Course Interactive jQuery Tutorial: Learn jQuery Step-by-Step
      Take an Interactive jQuery Training Course for Beginners to Quickly Master jQuery Events, Effects & More Learn PHP Online: PHP Basics Explained in an Interactive & Fun Manner
      An Interactive Tutorial for Beginners Who Want to Master PHP Basics in a Non-Boring Way The Complete Solidity Smart Contract Guide
      Master Solidity Programming Through Hands-On Experience Master Python Fundamentals the Fun Way: An Interactive Python Tutorial
      A Python Training Course for Absolute Beginners Who Wants to Master the Language Without Getting Bored A Responsive Web Design Course: Find Out How to Create a Responsive Website
      Make a Website Mobile-Friendly with a Step by Step, Responsive Web Design Tutorial Bootstrap Tutorial: Learn to Create Dynamic Websites in a Pinch
      Find Out How to Use Bootstrap the Fun Way by Using an Interactive Course An Interactive Java Tutorial: Learn by Practice!
      Learn Java From Scratch by Combining Theory with Hands-On Coding Experience Good to know
      Length of time users can access this course: lifetime Certification of completion included Redemption deadline: redeem your code within 30 days of purchase For a full description, specs, and instructor info, click here.

      Here's the deal:
      This Interactive Learn to Code Bundle normally costs* $112, but you can pick it up for just $29.99 for a limited time - that represents a saving of $82.01 (73%) off.

      >> Get this deal, or learn more about it <<
      See all discounted Online Courses. This is a time-limited offer.
      Get $1 credit for every $25 spent · Give $10, Get $10 · 10% off for first-time buyers.

      Not for you?
      If this offer doesn't interest you, why not check out the following offers:

      The Nintendo Gaming Bundle Giveaway 20% off Ivacy VPN subscription with coupon code IVACY20 NordVPN subscription at up to 68% off for a 2 year plan Private Internet Access VPN subscription at up to 71% off Unlocator VPN or SmartDNS unblock Geoblock with 7-day free trial Disable Sponsored posts · Other recent deals · Preferred partner software

      Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.

    • By News Staff
      Save 97% off the 2020 Learn to Code Full Stack Developer Certification Bundle
      by Steven Parker

      Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where you can save 97% off the 2020 Learn to Code Full Stack Developer Certification Bundle. Become a high-earning web developer with 50+ hours of instruction from top-tier instructors, including Rob Percival and John Elder.



      What's the deal?
      This deal consists of the following courses:

      Microsoft SQL Server & T-SQL Course For Beginners
      Understand the Benefits of SQL & Earn Big Bucks as a Skilled Developer Learn C# by Building Applications
      Understand the Concepts of C#6 &C#7 and Use Them to Build Real World .NET Console Apps Beginner Object-Oriented Programming in C# & .NET Core
      Climb Up the Developer Hierarchy by Mastering Object-Oriented Programming & Its Fundamental Concepts Using MySQL Databases with Python
      Learn MySQL Database with Python the Fast & Easy Way with John Elder HTML Programming for Everyone
      Learn to Build Awesome Websites Using HTML & the Bootstrap CSS Framework Intro to PHP for Web Development
      Learn PHP for Web Development & Become a Backend Coder in No Time The Complete C# Programming Course
      Master C# & .NET Framework with Code Challenges, Exercises, & Real-Life Examples with Rob Percival Advanced Python Training
      Go from Complete Beginner to a Python Language Expert Learn Angular by Creating a Web Application
      Master this Popular Web Dev Framework by Building an Interactive Virtual Cookbook Good to know
      Length of time users can access this course: lifetime Certification of completion included Redemption deadline: redeem your code within 30 days of purchase For a full description, specs, and instructor info, click here.

      What's the benefit?
      This 2020 Learn to Code Full Stack Developer Certification Bundle normally costs* $1,650, but you can pick it up for just $38.99 for a limited time - that represents a saving of $1,611.01 (97%) off.

      >> Get this deal, or learn more about it <<
      See all discounted Online Courses. This is a time-limited offer.

      Save even more!
      Stick with Neowin Deals and earn credit or even deeper discounts.

      Check out our recent deals here or on the Neowin Deals site. For every $25 spent, you get $1 credit added to your Neowin Deals account. Refer the deal for $10 credit via social media or email and if it results in a purchase of at least $10, you'll get $10 credit added to your account. 10% off for first-time buyers: be sure not to dismiss the popup offer to subscribe to email updates on the deals page in order to profit! Not for you?
      If this offer doesn't interest you, why not check out our giveaways on the Neowin Deals website? There's also a bunch of freebies you can check out here

      Miscellany and the fine print!
      In some cases, such as with Online Courses, a store credit refund within 15 days of purchase is possible if you are unhappy with it; this does not apply to all deals, so please do check the terms on the page before making a purchase.

      Check our other recent deals, before they expire, or our preferred partner software.

      How can I disable these posts? Click here.

      Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs. *Values or percentages mentioned above are subject to StackCommerce's own determination of retail pricing.

    • By News Staff
      Save 98% off this Ultimate Web Coding for Everyone Bundle
      by Steven Parker

      Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where you can save 98% off* this Ultimate Web Coding for Everyone Bundle. Dive deeper in the world of web coding with 8 courses on Python, Ruby, Javascript, PHP, HTML, Bootstrap 4, MySQL and Node.js



      What's the deal?
      This deal consists of the following courses:

      Python Programming for Everyone
      Learn Basic to Advanced Python 3 Programming in Only an Hour, Python 3 Download Included! Ruby Programming for Everyone
      Get Up to Speed with This Beginner-Friendly Language in Just One Hour JavaScript Programming for Everyone
      Learn to Code Javascript Like a Professional Programmer Intro to PHP for Web Development
      Learn PHP for Web Development & Become a Backend Coder in No Time HTML & Bootstrap CSS Programming for Everyone
      Learn to Build Awesome Websites Using HTML & the Bootstrap CSS Framework CSS Bootstrap 4 for Everyone
      Learn the Latest Version of Bootstrap 4 from Start to Finish & Build 3 Website Projects Intro to MySQL with Node.js: Learn to Use MySQL with Node
      Learn How to Use MySQL Databases with Node.js & Explore What These Databases Can Do Node.js Absolute Beginners Guide: Learn Node from Scratch
      Learn Node.js to Build Websites & Host Them Live on Heroku Webhosting Good to know
      Length of time users can access this course: lifetime Certification of completion included Redemption deadline: redeem your code within 30 days of purchase For a full description, specs, and instructor info, click here.

      What's the benefit?
      This Ultimate Web Coding for Everyone Bundle normally costs* $1,600, but you can pick it up for just $29 for a limited time - that represents a saving of $1,571 (98%) off.

      >> Get this deal, or learn more about it <<
      See all discounted Online Courses. This is a time-limited offer.

      Save even more!
      Stick with Neowin Deals and earn credit or even deeper discounts.

      Check out our recent deals here or on the Neowin Deals site. For every $25 spent, you get $1 credit added to your Neowin Deals account. Refer the deal for $10 credit via social media or email and if it results in a purchase of at least $10, you'll get $10 credit added to your account. 10% off for first-time buyers: be sure not to dismiss the popup offer to subscribe to email updates on the deals page in order to profit! Not for you?
      If this offer doesn't interest you, why not check out our giveaways on the Neowin Deals website? There's also a bunch of freebies you can check out here.

      Miscellany and the fine print!
      In some cases, such as with Online Courses, a store credit refund within 15 days of purchase is possible if you are unhappy with it; this does not apply to all deals, so please do check the terms on the page before making a purchase.

      Check our other recent deals, before they expire, or our preferred partner software for Private Internet Access and NordVPN deals.

      How can I disable these posts? Click here.

      Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs. *Values or percentages mentioned above are subject to StackCommerce's own determination of retail pricing.