• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
php mod % 3

#1
[eluser]webdezzo[/eluser]
Hey all,

This may or may not be a CI question (CI may have something useful to use for this) But, since this community rocks, I figured what the heck.

Lets say I have a 3 column layout like so:

Code:
<div id='column1'>
Content 1
</div>

<div id='column2'>
Content 2
</div>

<div id='column3'>
Content 3
</div>

And I select some data from my Database, that may return any number of records. I want to split this data into 3 arrays, that are equal (close plus or minus 1 due to odd / even) in length, so that echo the data from the 3 diffrent arrays in each column respectively. How could one go about doing this?

I would typically handle it if it were 2 columns with the mod function (% 2) but I am a little thrown off with the third column. I figure splitting the array based on the data would be the easiest method. Does CI have any easy array splitting functionality that I could say, take this data, split it into 3 arrays by taking the returned records and dividing them by 3?

Any ideas would be much appreciated!
Thanks!

#2
[eluser]Majd Taby[/eluser]
why don't you use modulo 3 ( % 3) ?

#3
[eluser]John_Betong[/eluser]
[quote author="Zaatar" date="1192777278"]why don't you use modulo 3 ( % 3) ?[/quote]

Why don't you use modulo 5 ( % 5)[b] ?

[b]controller.php
Code:
...
  ...
  ...

  //===========================================
  function five_col() {
    // $data    = $this->m_lib->m_first(NULL);
    // echo 'fred';die;
    $sql          = 'SELECT id, title FROM jokes'; //  WHERE id < 42
    $result     = $this->db->query($sql);
    
    foreach($result->result()as $row):
        switch($row->id % 5) {
            case 0    :    $data['a0'][] = anchor('/joke/show/'. $row->id, sprintf('&#x4d;  %s', $row->id, $row->title)); break;
            case 1    :    $data['a1'][] = anchor('/joke/show/'. $row->id, sprintf('&#x4d;  %s', $row->id, $row->title)); break;
            case 2    :    $data['a2'][] = anchor('/joke/show/'. $row->id, sprintf('&#x4d;  %s', $row->id, $row->title)); break;
            case 3    :    $data['a3'][] = anchor('/joke/show/'. $row->id, sprintf('&#x4d;  %s', $row->id, $row->title)); break;
            case 4    :    $data['a4'][] = anchor('/joke/show/'. $row->id, sprintf('&#x4d;  %s', $row->id, $row->title)); break;

/*            
            case 0    :    $data['a0'][] = sprintf("&#x4d;  &#x10;s", $row->id , $row->title); break;
            case 1    :    $data['a1'][] = sprintf("&#x4d;  &#x10;s", $row->id , $row->title); break;
            case 2    :    $data['a2'][] = sprintf("&#x4d;  &#x10;s", $row->id , $row->title); break;
            case 3    :    $data['a3'][] = sprintf("&#x4d;  &#x10;s", $row->id , $row->title); break;
            case 4    :    $data['a4'][] = sprintf("&#x4d;  &#x10;s", $row->id , $row->title); break;
            case 5    :    $data['a5'][] = sprintf("&#x4d;  &#x10;s", $row->id , $row->title); break;
*/        
        }//end switch
    endforeach;
    
        $show    = $this->load->view('_five_col', $data, TRUE);
        echo $show;            
        
    // return $this->m_sql($data);

    // $this->j_view($data);
  }//endfunc
&nbsp;

View: _five_col.php
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
&lt;html lang="en-GB"&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt;
  &lt;title&gt;Five Columns&lt;/title&gt;
  &lt;base href="&lt;?php echo base_url() .APPPATH ?&gt;" /&gt;
  &lt;link   type="text/css" href="css/ss_pink.css" rel="stylesheet" /&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
  &lt;meta name="author" content="John_Betong" /&gt;
  &lt;meta name="keywords" content="&lt;?php echo isset($head_keywords) ? $head_keywords : 'jokes' ?&gt; " /&gt;
  &lt;meta name="description" content="Soon to be the best joke site on the web" /&gt;
  &lt;meta http-equiv="imagetoolbar" content="no" /&gt;
  &lt;link rel="icon" href="favicon.ico" type="image/x-icon" /&gt;
  &lt;link rel="shortcut icon" href="anetizer.ico" type="image/x-icon" /&gt;
  &lt;?php /* HTML JavaScript code here */ ?&gt;
  &lt;?php /* http://www.sitepoint.com/article/simply-javascript/2 */ ?&gt;
  &lt;style type="text/css"&gt;
        body                {background:#eee none; color:#00f; border:0; margin:0; padding:0; foint-family:arial, verdana; font-size:20px}
        p                        {margin:0 0 1em 0}
        h1                    {text-align:center}
        #container    {background:#ccc none; color:#f0f; width:1000px; margin: 3em auto; border:outset 4px}
        
        .column0, .column1, .column2, .column3, .column4 {color:#000; clear:right; float:left; width:19%; border:dotted; margin:1em auto}
        .column0    {background:#cff none}
        .column1    {background:#ffc none}
        .column2    {background:#cfc none}
        .column3    {background:#ff9 none}
        .column4    {background:#9f9 none}
        .column5    {background:#9ff none}
    &lt;/style&gt;
&lt;/head&gt;

&lt;?php
    function floated_box($a=array(), $col='column0')    {
        
        echo "<div class='$col'>";
             foreach($a as $row):
                     echo '<p>' .$row .'</p>';
             endforeach;
        echo '</div>';
    }
    
?&gt;    
        
&lt;body&gt;
    <div id='container'>
        <h1>Johns-Jokes</h1>
        
        &lt;?= floated_box($a1, 'column1') ?&gt;
        &lt;?= floated_box($a2, 'column2') ?&gt;
        &lt;?= floated_box($a3, 'column3') ?&gt;
        &lt;?= floated_box($a4, 'column4') ?&gt;
        &lt;?= floated_box($a0, 'column0') ?&gt;
    </div>    
            
    
&lt;/body&gt;
&lt;/html&gt;

#4
[eluser]Majd Taby[/eluser]
John_Betong, the switch statement in your controller is completely unnecessary. In my experience, whenever you duplicate code like that, there's probably a better way to do it:

Code:
$data['a'.($row->id % 5)][] = anchor('/joke/show/'. $row->id, sprintf('&#x4d;  %s', $row->id, $row->title));

That should work just as well.

#5
[eluser]John_Betong[/eluser]
&nbsp;
Many thanks Zaatar for your suggestions, Here are the results:

http://johns-jokes.com/joke/five_col

&nbsp;
Code:
foreach($result->result()as $row):
            $data['a'.($row->id % 5)][] = anchor('/joke/show/'
                                        . $row->id, sprintf(" %d  &nbsp;&nbsp;  %s", $row->id, $row->title));    
    endforeach;

#6
[eluser]Pygon[/eluser]
Happened to this from your other page...

I'm more concerned with how much slower your page processes because you calculate the modulus of almost 1000 numbers.

Code:
$i = 0;
$cols = 5;
foreach($result->result() as $row)
{
  if ($i == $cols ) $i = 0;
  $data['a'.$i][] = anchor('/joke/show' . $row->id, sprintf(" %d &nbsp;&nbsp; %s",$row->id, $row->title));
  $i++;
}

is faster, taking about 1/3rd of the time.

#7
[eluser]John_Betong[/eluser]
Hi Pygon,

I was curious to see how much faster your code was so took the trouble to modify my code:

contoller
Code:
// Benchmark different methods  of calculating links
  $this->benchmark->mark('code_start');
  if (0===$test) { // slow method
    $data['joketitle']    = 'Five column using  <b>% 5</b>';
    foreach($result->result() as $row):
    $data['a'.($row->id % 5)][] = anchor('/joke/show/'
                                . $row->id, sprintf("&#x4d;  &nbsp;&nbsp;  %s", $row->id, $row->title));    
    endforeach;
      
  }else{
   $data['joketitle'] = 'Five column using  <b>$i++</b>';
   $i    = 0;
   $cols = 5;
   foreach($result->result() as $row) {
     if ($i == $cols ) {
       $i = 0;
     }
    $data['a'.$i][] = anchor('/joke/show/'
                    .$row->id, sprintf(" %d    &nbsp;&nbsp; %s",$row->id, $row->title));
                     $i++;
    }//endforeach
  }// end else
  $this->benchmark->mark('code_end');
  $data['joketitle'] .= ' Elapsed time ==> ' .$this->benchmark->elapsed_time('code_start','code_end');
&nbsp;
Test results shown in the title ("Five column using $i++ Elapsed time ==>"):
&nbsp;
&nbsp;&nbsp;using++

&nbsp;&nbsp;using %5
&nbsp;
Cheers,

John_Betong
&nbsp;

#8
[eluser]Pygon[/eluser]
Hi John --

I took a further look at my results and it seemed I had some stuff out of whack with my benchmarking system. I tore it all up and rewrote it again -- modulos seems to be the faster of the two, as well as !empty() over strlen()>0 and $i++ over $i+=1, in case you wanted to know, haha. Anyway, my appologies.

#9
[eluser]John_Betong[/eluser]
Hi Pygon,

Many thanks for your code I learnt how easy it was to use the BenchMark Class, This will no doubt come in handy in the future.

I would not have imagined Modulos to be much faster and think it was the repeated if test to see if $i==0 was the time grabber.

Empty() just tests for Null, 0 or an empty string whereas strnlen() should test and cater for string lengths, etc. Maybe also allocate memory for the counter.

A long time ago I read why $i++ is faster than $i+=1 and think the reason is something to do with just shifting a bit in the byte whereas the +1 must use the addition routine. I have just remembered the good old days and having to write a multiplication routine using Z80 Assembler - no mean task!

Aren't computers fun Smile

Cheers,

John_Betong
&nbsp;

#10
[eluser]mdriscol[/eluser]
Hey, is there a way I can do this without putting it into html in the controller. I want 3 columns but I don't want to write it as a row and html.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.