I am sure the title is not even right on this one.
Here is the issue , I have 3 columns and 6 results
that are displayed like this
Column1 Column2 Column3
result1 result3 result5
result2 result4 result6
but need them like this
Column1 Column2 Column3
result1 result2 result3
result4 result5 result6
my array holds all 6 results and so far I see I need to pick every 0 and 2nd to be displayed in column1 and continue( array starts at 0).
the code is pretty large but the main part for switching results is here
$count = count($result);
for ($result = 0; $result < $count; $result++) {
$getorder= "";
if ($count != 1) {
if ($result == 0) $getorder= "first";
if ($result == $count - 1) $getorder= "last";
}
echo '<div class="'.$getorder.'width'.intval(100 / $count).'">'.$mycolumn[$result].'</div>';
}
so this here should have some kind of division. Here is just dumb example
$mycolumn[$result % X == X]
i hope I did not confuse you and you get the idea. If you ask yourself why i don't just do rows instead columns , answer is complete css reconstructions. whit this here figured out I can target the results and keep columns and css as they are
Don't use ($result / 3) since you can have seriuous rounding problem.
Since to me it's not very clear the name of your vars I post you a php generic code and it is:
echo '<div class="result">';
for($i = 0; $i < $columnNum; $i++)
{
echo '<div class="column">';
for($j = $i; $j < $resultNum; $j += $columnNum)
echo '<label class="value">' . array[j] . "</label>";
echo '</div>';
}
echo '</div>';
Just change the vars name with your needs and this is the solution to your problem.
$mycolumn[intval($result / 3) + intval(($result % 3) * $count / 3)]
Demo http://codepad.viper-7.com/hdSi6b
Working flawlessly.
You can change whole code as AurelioDeRosa said.
Related
I have the following code which with the following variables set numberofColumns = 2 and numberArticles = 10, will create 2 columns for articles, the article order is from left to right (column1 to column2) going down the page.
Id just like to add some code </div><div class="whatever"> after every 2nd article.
Any help would be much appreciated.
if ($numberColumns >= 1) {
$columnArticles = intval(($numberArticles + $numberK2Articles) / $numberColumns);
}
$columns = array();
for($columnIndex = 0; $columnIndex < $numberColumns; $columnIndex++) {
$columns[$columnIndex] = '<div class="column col-' . ($columnIndex + 1) . '">';
}
$articleIndex = 0;
while($articleIndex < count($articles)) {
foreach ($columns as $columnIndex => $column) {
if (isset($articles[$articleIndex])) {
$columns[$columnIndex] .= modCTRandomArticleHelper::getArticleHtml($params, $articles, $articleIndex);
$articleIndex++;
}
}
}
for($columnIndex = 0; $columnIndex < $numberColumns; $columnIndex++) {
echo $columns[$columnIndex] . '</div>';
}
I've always used the Modulus operator (%) to determine if my current index was one of n rows. $index % 2 returns 0 for every second row. $index % 3 returns 0 for every third row, and so on.
http://php.net/manual/en/internals2.opcodes.mod.php
The first comment on that page suggests that a bitwise operation is more efficient when you just need to determine odd or even. So, $index & 1 (odd) is a faster alternative to !$index % 2 (odd).
I have a little script that prints a certain amount of rows in a mysql database.
Is there any way to make it so that after every second row it prints, there is a line break inserted?
Adding a line break after every row is simple, but I don't know how to add one after every other row. Is that possible?
You write "script" but in tags you have PHP, so I suppose you need PHP code:
foreach ($rows as $row) {
if ($i++ % 2) {
// this code will only run for every even row
}
...
}
$i=1;
while ($row = mysql_fetch_array($query))
{
//your code
if ($i % 2 == 0)
echo '<br>';
$i++;
}
add new variable before the loop
$i = 0;
then in your loop add
if ($i != 0 && $i%2 == 0)
echo '<br/>';
Depending on the language, something like this should do it: (in php) (where $arr is an array of results)
$str = '';
$i = 0;
for ($i=0; $i<count( $arr ); $i++)
{
if ( ( $i + 1 ) % 2 === 0 )
{
$str .= $arr[$i] . '<br />';
}
else
{
$str .= $arr[$i];
}
}
echo $str;
Use php and modulo.
such as
if($i % 3)
{
echo '<br />'..
If you need to do this inside the query for some reason, you could use something like
SELECT
<your fields>,
IF (((#rn:=#rn+1) % 3)=0,'<br>','') as brornot
FROM
<your tables and joins>,
(#rn:=0)
I need to create 3 HTML columns in PHP with data returned from MySQL. I would like the data split evenly between all 3 columns... How would I go about doing this?
You could try doing something like this:
$result = mysql_query("SELECT value FROM table");
$i = 0;
echo '<table><tr>';
while ($row = mysql_fetch_row($result)){
echo '<td>' . $row[0] . '</td>';
if ($i++ == 2) echo '</tr><tr>'
}
echo '</tr></table>';
note this table has the values ordered like
1 2 3
4 5 6
7 8 9
If you wanted it vertically like
1 4 7
2 5 8
3 6 9
Then you should do something like
$result = mysql_query("SELECT value FROM table");
$data = Array();
while ($row = mysql_fetch_row($result)) $data[] = $row;
for ($i = 0; $i < count($data) / 3; $i++){
echo '<table><tr>';
for ($j = 0; $j < 3; $j++){
echo '<td>' . $data[ $i + $j * 3] . '</td>';
}
echo '</tr><tr>'
}
echo '</tr></table>';
You can create an HTML table and then use a PHP foreach loop to loop through the MySQL result set and put each field in its own table. At the end of each record returned by the MySQL query, end the table row and start a new one.
A small detail, if return more entries than the "fetch_row" use "break", based on the answer from #Robbie: Spliting mysql data in 3 columns error -3-columns-error
I'm querying a database for names that are numbered 1-26 alphabetically. I have the following code, but since HTML is structured tr then td, the table appears alphabetically by row as opposed to by column. How can I make it appear in order by column?
$query = mysql_query("SELECT name FROM people WHERE main=1 ORDER BY id");
$i = 0;
while($result = mysql_fetch_array($query)) {
$name = $result['name'];
if ($i % 5 == 0) echo "<tr>\n";
echo "<td width=\"150\">";
echo "".$name."<br />";
echo "</td>\n";
$i++;
if ($i % 5 == 0) echo "</tr>\n";
};
alpha beta charlie
delta echo foxtrot
vs.
alpha charlie echo
beta delta foxtrot
Also, I'm open to reworking the code if there's a more efficient way.
You could just access the output array in strides. Compute how many rows you need as the number of results divided by 5, and use the row count as the stride.
$ncols = 5;
$nrows = $nresults / $ncols + ($nresults % $ncols == 0 ? 0 : 1);
for ($i = 0; $i < $nrows; $i++)
{
// start row
for ($j = 0; $k < $ncols; $j++)
{
// print $results[$nrows * $j + $i]
}
// end row
}
You'll have to transfer your query results into an array $results first. Since you'll have to know the total number of results, this is sort of mandatory, though I'd be curious if anyone has a solution that can work while fetching the results.
Update: See Justin's answer for a cool solution that grows the output while fetching the query results line by line. Since it's currently being worked on, here's a summary (credits to Justin):
$nresults = mysql_num_rows($query);
$ncols = 5;
$nrows = (int) ceil($nresults / $ncols);
$i = 0; $cols = array_fill(0, $nrows, "");
while ($result = mysql_fetch_array($query))
$cols[$i++ % $nrows] .= "<td>$result['name']</td>";
echo "<tr>" . implode("</tr><tr>", $cols) . "</tr>";
Edit:
After the discussion in the comments between myself, Kerrek SB and the OP bswinnerton, the following code seems to be the most effective:
$columns = 3;
$rowcount = mysql_num_rows($query);
$rows = ceil($rowcount / $columns);
$rowdata = array_fill(0, $rows, "");
$ctr = 0;
while ($result = mysql_fetch_array($query))
$rowdata[$ctr++ % $rows] .= '<td>'.$result['name'].'</td>';
echo '<tr>'.implode('</tr><tr>',$rowdata).'</tr>';
This will create three columns, filled vertically (my original answer would create three rows). It also properly initializes the array (preventing PHP warnings), yields a correct row count for result counts that aren't divisible by the column count, and incorporates Kerrek's clever "calc-row-in-the-subscript" trick.
Original Post:
You could use arrays and implode() This way, you only have to make one pass through your results:
$row = 0;
$rows = 3;
$rowdata = array();
while($result = mysql_fetch_array($query))
{
if ($row >= $rows) $row = 0;
$rowdata[$row++] .= '<td>'.$result['name'].'</td>';
}
echo '<tr>'.implode('</tr><tr>',$rowdata).'</tr>';
I am attempting to show data in rows of three like this (notice the number of items will not always be even):
abcd defg hijk
lmno pqrs tuvw
xyz1 2345 6789
1011 1213
I am struggling to get the logic right to do this (this is in a foreach() loop).
I know I have to have some if($i %3 == 0) logic in there.. But I'm a bit stuck.
Can anyone help me out?
$a = array('abcd','defg','hijk','lmno');
for ($i = 0; $i < count($a); $i++) {
if ($i && $i % 3 == 0)
echo '<br />';
echo $a[$i].' ';
}
It's better to use a for loop as:
// run $i for each index in the array.
for($i=0 ; $i<count($arr) ; $i++) {
// if $i is non-zero and is divisible by 3 print a line break.
if ($i && $i % 3 == 0) {
echo "<br />";
}
// print the element at index $i.
echo $arr[$i].' ';
}
Code in action
Pseudo-code since I don't know PHP (and you asked for the logic which tends to be the same across all procedural languages):
perline = 3
i = 0
foreach item in list:
if i > 0 and (i % perline) == 0:
print newline
if (i % perline) != 0:
print space
print item
i = i + 1
This will both output a line separator before elements 3, 6, 9 and so on (first element being 0) and place whatever desired spacing you want before the second and third elements on each line. You can just use a different value for perline to change the number output on each line.