Simplifying Code

Discussion in 'PHP' started by crazyryan, Feb 24, 2009.

  1. #1
    Hey

    Could anyone give me a hand simplifying this code to use an array or something:

    http://pastebin.com/m6eec7582

    Right now it's a bit long winded and I'm sure I could use a loop/array of some sort to shorten it down and make it more efficient.

    Thanks
     
    crazyryan, Feb 24, 2009 IP
  2. wmtips

    wmtips Well-Known Member

    Messages:
    601
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #2
    Just a quick try:
    <?
     $days = array(
     'mon'=>array('name'=>'Monday'),
     'tue'=>array('name'=>'Tuesday'),
     'wed'=>array('name'=>'Wednesday'),
     'thu'=>array('name'=>'Thursday'),
     'fri'=>array('name'=>'Friday'),
     'sat'=>array('name'=>'Saturday'),
     'sun'=>array('name'=>'Sunday'));
    
     while($row = mysql_fetch_object($query))
     {
      if (isset($days[$row->day]['value']))
       $days[$row->day]['value'] .= '<p>' . $row->assignment_id . '</p>';
      else
       $days[$row->day]['value'] = '<p>' . $row->assignment_id . '</p>';
     }
    
     foreach ($days as $d)
     {
      echo "<h2>{$d['name']}</h2>";
      if (isset($d['value']))
       echo $d['value'];
     }
    ?>
    PHP:
     
    wmtips, Feb 24, 2009 IP
  3. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #3
    I think this will do, untested.

    
    <?php
    $aMon = ''; $aTue = ''; $aWed = ''; $aThu = ''; $aFri = ''; $aSat = ''; $aSun = '';
    $day_array = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
    
    while($row = mysql_fetch_object($query)) {
    $rowday = 'a'.ucfirst($row->day);
    ${$rowday} .= '<p>' . $row->assignment_id . '</p>';
    }
    
    foreach ($day_array as $day) {
    $prepare_var = 'a'.strtoupper($day[0]).$day[1].$day[2];
    echo "<h2>$day</h2>".${$prepare_var};
    }
    ?>
    
    PHP:
    Depends on your server, this line may be not neccessary.
    - ads2help
     
    ads2help, Feb 24, 2009 IP