saving strings into an array - php

I've got a query which finds the top 10 most loaned books in my loan table, however i want to store these ten values into a single array so that I can then use the array again. Here is the code I have so far... Thanks for any help in advance!
//select a database to work with
$selected = mysql_select_db("ds2",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT book.title, book.book_id, count(book.book_id) AS count_book_id, loan.book_id FROM book
INNER JOIN loan ON book.book_id = loan.book_id
GROUP BY book.book_id ASC
ORDER BY count(book.book_id) DESC");
$titles = array();
while($row = mysql_fetch_array($result))
{
echo $row['title'];
echo "<br>";
}
echo "<br><br>";
for($index = 1; $index <= 10; $index++)
{
array_push($titles,$result[$row]);
print_r($titles);
echo "<br>";
}

Rather than echo $row['title'] You can use below code to store them into an array
$titles[] = $row['title'];
Use array notion to access them later.
$titles[0]; // 1st item
$titles[1]; //2nd item
You can even use a foreach loop to loop through all the items.
foreach($titles[] as $title)
echo $title;
Below will allow you to get a comma separated string(Just for your information if you need it)
$comma_separated_titles = implode(",", $titles);

Try,
while($row = mysql_fetch_array($result))
{
echo $row['title'];
$arr[] = $row['title']; //Store in an array
echo "<br>";
}
echo "<br><br>";
//Since you need only 10 values, else this for loop is not required.
for($index = 1; $index <= 10; $index++)
$titles[] = $arr[$index]['title'];
unset($arr); //unset the original array if you don't need it anymore.
print_r($titles); //Print top 10 values
echo "<br>";

You should fill your array in the loop, not after it in a separate loop:
$count = 0;
while($row = mysql_fetch_array($result))
{
echo $row['title'];
echo "<br>";
if ($count < 10)
{
array_push($titles, $row);
}
$count++;
}

Related

combining values from mysql seperated by comma using explode

I have two columns in my mysql table pro_id and pro_page. Each column contains integer values separated by comma.
example,
pro_id pro_page
-------- ------------
1,2,3 1,1,1
2 1
3,4 2,1
I want to combine first integer value from pro_id and first integer value from pro_page, second integer value from pro_id and second integer value from pro_page and so on.
For example,
from first row, result should be 11 21 31
from second row, result should be 21
from third row, result should be 32 41
I have tried using the below code,
$query = "SELECT pro_id, pro_page from tbl_checkout";
$result = mysqli_query($c,$query)or die(mysqli_error($c));
$length = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result1))
{
$pro_id[] = $row["pro_id"];
$pro_page[] = $row['pro_page'];
}
for($i=0; $i<$length1; $i++)
{
$pro_id = explode(",", #$pro_id[$i]);
$pro_page = explode(",", #$pro_page[$i]);
foreach($pro_id as $product_id) {
$product_id = $product_id;
echo $product_id;
}
foreach($pro_page as $product_page) {
echo $product_page;
}
}
Now the result is,
from first row, 123111
from second row, 21
from third row, 3421
Is there any way to achieve what i want. I have tried a lot.
After fetching the array from database do the following:
$output = array();
while($row = mysqli_fetch_array($result1))
{
$pro_id = explode(',' , $row["pro_id"]);
$pro_page = explode(',' , $row['pro_page']);
for($i = 0; $i< count($pro_id); $i++)
{
$output[$i] = $pro_id[$i] . $pro_page[$i];
}
return $output;
}
You can do it via single foreach if you numbers amount is same in both arrays
$products = explode(",", #$pro_id[$i]);
$pages = explode(",", #$pro_page[$i]);
foreach( $products as $k => $product_id){
$product_page = $pages[$k];
echo $product_id . $product_page . " ";
}
Try below code:
$query = "SELECT pro_id, pro_page from tbl_checkout";
$result = mysqli_query($c,$query)or die(mysqli_error($c));
$length = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result1))
{
$pro_id[] = $row["pro_id"];
$pro_page[] = $row['pro_page'];
}
for($i=0; $i<$length1; $i++){
$pro_id = explode(",", #$pro_id[$i]);
$pro_page = explode(",", #$pro_page[$i]);
$newProduct_id = '';
foreach($pro_id AS $keyIndex => $product_id) {
$newProduct_id = $pro_id[$keyIndex] . $pro_page[$keyIndex] . " ";
echo $newProduct_id;
}
}
You have to loop over both arrays at once. Easiest when using for():
$query = "SELECT pro_id, pro_page from tbl_checkout";
$result = mysqli_query($c,$query)or die(mysqli_error($c));
$length = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result1))
{
$pro_id[] = $row["pro_id"];
$pro_page[] = $row['pro_page'];
}
for($i=0; $i<$length1; $i++)
{
// don't assign to $pro_id and $pro_page as variable name: it will mess up your data!
$tmp_id = explode(",", $pro_id[$i]);
$tmp_page = explode(",", $pro_page[$i]);
for($c=0; $c < count($tmp_id)) {
echo $tmp_id[$c];
echo $tmp_page[$c];
}
}
Another problerm is that you use $pro_id and $pro_page for two different purposes. You use it for storage of db results and to store the exploded numbers from this data. Use different variable names.

Can you use a for loop to create array names?

I am pulling data from a database and I want to create array names on the fly.....group1, group2...etc using a for loop. I wonder if this is possible at all? The code below obviously doesn't work and I'm only including it to demonstrate what I'm trying to do. Any help would be much appreciated!
<?php
for ($i=1; $i <=40; $i++){
$group.$i = [];
}
?>
Its not so much "array names" that you are looking for as a much as a nested array. $group[$i] would give you a nested array. eg
for ($i=1; $i <=40; $i++){
$group[$i] = [];
}
$group[1][] = 'foo';
echo $group[1][0];
// prints: foo
Something like this ? This works 100%
// $result = $conn->query($sql);
$i = 0;
$all = array();
while($row = $result->fetch_assoc()) {
$i++;
$arr[$i]['id'] = $row['id'];
$arr[$i]['firstname'] = $row['first_name'];
$arr[$i]['lastname'] = $row['last_name'];
$all[] = $arr[$i];
}
echo '<pre>';
echo print_r($all);

mysql_fetch_array while loop

I have a while loop that contains another while loop. Both loops are iterating over different mysql result sets. The problem is that the second time the outer while loop calls the inner while loop it doesn't run. Does Mysql_fetch_row discard itself after it has been iterated over?
Here is what the code looks like:
$counter = 0;
while ($r = mysql_fetch_row($result)){
$col = "";
$val = "";
while($d = mysql_fetch_row($dictionary)){
$key = $d[0];
for($i= 0; $i< count($tableColumNames); $i++){
if($tableColumNames[$i] == $key){
$col .= "`".$d[1]."` ,";
$val .= "`".$r[$i]."` ,";
/* echo $tableColumNames[$i]." table ColumnName <br>";
echo $d[1]." key<br>"; */
}
}
echo $key."round".$counter."<br>";
}
var_dump ($col);
var_dump ($val);
$counter++;
echo $counter;
}
And here is what the output is like: You can see that the $result holds four records and the output is showing that the loop is working correctly. However, the inner loop over the $dictionary result set doesn't run the second time $result is being iterated over. Any ideas why? I tried to use mysql_fetch_array as well but still the same result.
Thanks
When ever you are calling mysql_fetch_row($dictionary) It gives you a particular column details in the row and it deletes it from the $dictionary array.
So there are no elements for next use.
Instead of declaring $dictionary outside declare it in while loop. It will solve your problem.
$counter = 0;
while ($r = mysql_fetch_row($result)){
$col = "";
$val = "";
$dictionary=("Select * from database");//your own logic
while($d = mysql_fetch_row($dictionary)){
$key = $d[0];
for($i= 0; $i< count($tableColumNames); $i++){
if($tableColumNames[$i] == $key){
$col .= "`".$d[1]."` ,";
$val .= "`".$r[$i]."` ,";
/* echo $tableColumNames[$i]." table ColumnName <br>";
echo $d[1]." key<br>"; */
}
}
echo $key."round".$counter."<br>";
}
var_dump ($col);
var_dump ($val);
$counter++;
echo $counter;
}
or you can use mysql_data_seek().

Display PHP Data in 2 Columns

Here's my code:
echo "<table><tr>";
$count = 1;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
extract($row);
$data = $row['info'];
echo "<td>".$data."</td>";
if ($count++ % 2 == 0) {
echo "</tr><tr>";
}
}
echo "</tr></table>";
The above code works as:
=========
= 1 = 2 =
= 3 = 4 =
= 5 = 6 =
=========
But how do I display the info in this format?
=========
= 1 = 4 =
= 2 = 5 =
= 3 = 6 =
=========
Actually, you don't need to parse array to another form...
<?php
$a = array(1,2,3,4,5,6,7);
$c = ceil(count($a)/2);
echo "<table>";
for($i=0; $i<$c;++$i){
echo "<tr><td>{$a[$i]}</td><td>{$a[$i+$c]}</td></tr>";
}
echo "</table>";
?>
Ofcourse you need to modify this code by adding db operations (like mysql_num_rows instead of count) but it works fine: enter link description here
Thanks, guys! I appreciate all your help, but this code works perfect for me. I just want to share it with others who may find this helpful. :)
$tmp=array();
$columns=2;
$row=ceil(mysql_num_rows($result)/$columns);
for ($x =1; $x <= $columns; $x++)
for ($y = 1; $y <= $row; $y++)
$tmp[$x][$y]=mysql_fetch_array($result);
echo "<table align=center width=\"50%\">\n";
for ($y =1; $y <= $row; $y++) {
echo "<tr>";
for ($x = 1; $x <= $columns; $x++)
if (isset($tmp[$x][$y]['ID']))
echo "<td>".$tmp[$x][$y]['info']." </a></td>";
else
echo "<td></td>";
echo "</tr>\n";
}
echo "</table>\n";
A brief PSA... the mysql_ extension is depreciated and will eventually be removed. You need to start using mysqli_ now.
You need to parse your data first. Once you've done that, generating the table is easy. This should work for all data sets
echo "<table>";
$count = 1;
$col1 = $col2 = array();
$rowcount = round(mysql_num_rows($result) / 2);
while($row = mysql_fetch_assoc($result)) {
if($count > $rowcount) $col2[] = $row['info'];
else $col1[] = $row['info'];
$count++;
}
$counter = 0; // Arrays start with 0
foreach($col1 as $row) { // $col1 will always be >= $col2
$row2 = (isset($col2[$counter])) ? $col2[$counter] : "";
echo "<tr><td>" . $row . "</td><td>" . $row2 . "</td></tr>";
$counter++;
}
echo "</table>";
This is untested, but you can acheive this cleanly with 2 loops. Build up the left and right columns based on the the $count variable. Build the HTML all the way up, then echo it.
Edit: I didn't realize you were dividing the data in half and placing the first half on the left column of the table. I have changed the code below to do this.
<?php
$left = array();
$right = array();
$count = 1;
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($count <= $num_rows/2) {
array_push($left, $row['info']);
} else {
array_push($right, $row['info']);
}
$count++;
}
$html = "<table>";
for ($i = 0; $i < $count; $i++) {
$html .= "<tr><td>"
. htmlentities($left[$i])
. "</td><td>"
. htmlentities($right[$i])
. "</td></tr>";
}
$html .= "</table>";
echo $html;
?>
Here is some php magic that could shorten that code for a bit
<?php
$array = range(1, 20);
$count = 2;
$out = array_chunk($array, ceil(count($array)/$count));
array_unshift($out, null);
$out = call_user_func_array("array_map", $out);
?>
<table>
<?php foreach ($out as $row) : ?>
<tr>
<?php foreach($row as $column) : ?>
<td><?php echo( $column ); ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
Also, i would recommend you switch your database-related code to PDO. Besides all those nice features, like auto-escaping, you can easily get an array of elements from your DB query, without all this mysql_fetch_array nonsense.

Print Terms in Node in Multiple Columns Sorted in Downward Order

I have approximately 20 content-taxonomy check boxes from one field ("features"). The checked terms display in node-example.tpl.php. I am trying to show these content-taxonomy terms in two columns displayed/sorted in a downward order instead of across.
I am trying to cobble two bits of code to accomplish this...but my php skills are not yet up to the challenge. I can't get all of the array values generated in the foreach loop to be recognized by the second section of code.
The code below was taken (and modified) from the following sources:
http://drupal.org/node/312812
roscripts.com/PHP_display_data_on_columns-127.html
I am trying to use the following code in my node-example.tpl.php file.
<?php
echo '<table>';
foreach ($node->field_features as $delta => $value){
$term = taxonomy_get_term($node->field_features[$delta]['value']);
$term_name = check_plain($term->name);
}
// Default # of Columns
$numcols = 2;
// Number of Items
$numitems = count($term_name);
// Number of Rows
$numrows = ceil($numitems/$numcols);
for ($row=1; $row <= $numrows; $row++)
{
$cell = 0;
echo ' <tr>'."\n";
for ($col=1; $col <= $numcols; $col++)
{
echo ' <td>'."\n";
if ($col===1)
{
$cell += $row;
print $term_name[$cell - 1];
}
else {
$cell += $numrows;
print $term_name[$cell - 1];
}
echo ' </td>'."\n";
}
echo ' </tr>'."\n";
}
echo '</table>';
?>
Ok, I got this to work using the answer to another foreach-loop question/answer on this site.
Declare the $items array outside the
loop and use $items[] to add items to
the array.
This is the final code that does exactly what I wanted.
<?php
echo '<table>';
$items = array();
foreach ($node->field_features as $delta => $value)
{
$term = taxonomy_get_term($node->field_features[$delta]['value']);
$term_name = check_plain($term->name);
$items[] = $term_name;
}
// Default # of Columns
$numcols = 2;
// Number of Items
$numitems = count($items);//print $numitems;
// Number of Rows
$numrows = ceil($numitems/$numcols);//print $numrows;
for ($row=1; $row <= $numrows; $row++)
{
$cell = 0;
echo ' <tr>'."\n";
for ($col=1; $col <= $numcols; $col++)
{
echo ' <td>'."\n";
if ($col===1)
{
$cell += $row;
print $items[$cell - 1];
}
else {
$cell += $numrows;
print $items[$cell - 1];
}
echo ' </td>'."\n";
}
echo ' </tr>'."\n";
}
echo '</table>';
?>
You can use theme('table', $headers, $rows) to render your table using the theme engine.
// Default # of Columns
$numcols = 2;
$rows = array();
$cell_count = 0;
foreach ($node->field_features as $delta => $value) {
$term = taxonomy_get_term($node->field_features[$delta]['value']);
$term_name = check_plain($term->name);
$cell_count += 1;
$row_index = floor($cell_count / $numcols);
$rows[$row_index][] = $term_name;
}
print theme('table', array(), $rows);

Categories