Getting double numbers from array_rand - php

I want to create a Bingo script. I have already coded a 6x6 pattern with random numbers which have a certain range on each line. BUT now it outputs the same number multiple times, i want it to be all random numbers, can someone help me out?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Indzendopdracht 051R3</title>
</head>
<body>
<?PHP
function printBingocard(){
$bingoNumbers = array(
"rij_1" => array(10,11,12,13,14,15,16,17,18,19),
"rij_2" => array(20,21,22,23,24,25,26,27,28,29),
"rij_3" => array(30,31,32,33,34,35,36,37,38,39),
"rij_4" => array(40,41,42,43,44,45,46,47,48,49),
"rij_5" => array(50,51,52,53,54,55,56,57,58,59),
"rij_6" => array(60,61,62,63,64,65,66,67,68,69)
);
$rand_keys = array_rand($bingoNumbers, 1);
$rows = array();
foreach($bingoNumbers["rij_1"] as $bn_rij1){
if($bn_rij1 > 10 && $bn_rij1 <= 16){
$rows["row1"][]="<td>" . $bingoNumbers["rij_1"][array_rand($bingoNumbers["rij_1"])] ."</td>";
}
}
foreach($bingoNumbers["rij_2"] as $bn_rij2){
if($bn_rij2 > 20 && $bn_rij2 <= 26){
$rows["row2"][]="<td>" . $bingoNumbers["rij_2"][array_rand($bingoNumbers["rij_2"])] ."</td>";
}
}
foreach($bingoNumbers["rij_3"] as $bn_rij3){
if($bn_rij3 > 30 && $bn_rij3 <= 36){
$rows["row3"][]="<td>" . $bingoNumbers["rij_3"][array_rand($bingoNumbers["rij_3"])] ."</td>";
}
}
foreach($bingoNumbers["rij_4"] as $bn_rij4){
if($bn_rij4 > 40 && $bn_rij4 <= 46){
$rows["row4"][]="<td>" . $bingoNumbers["rij_4"][array_rand($bingoNumbers["rij_4"])] ."</td>";
}
}
foreach($bingoNumbers["rij_5"] as $bn_rij5){
if($bn_rij5 > 50 && $bn_rij5 <= 56){
$rows["row5"][]="<td>" . $bingoNumbers["rij_5"][array_rand($bingoNumbers["rij_5"])] ."</td>";
}
}
foreach($bingoNumbers["rij_6"] as $bn_rij6){
if($bn_rij6 > 60 && $bn_rij6 <= 66){
$rows["row6"][]="<td>" . $bingoNumbers["rij_6"][array_rand($bingoNumbers["rij_6"])] ."</td>";
}
}
echo "<table>";
foreach($rows as $row){
echo "<tr>";
foreach($row as $r){
echo $r;
}
echo "</tr>";
}
echo "</table>";
}//END OF FUNCTION
printBingocard();
?>
</body>
</html>

Why not just use shuffle()? As is right now, you're never checking for array_rand() producing a duplicate number, so yeah - you'll get dupes.
This is far more efficient:
foreach(array_keys($bingoNumbers) as $key) {
shuffle($bingoNumbers[$key]);
}
One SINGLE loop, and each of those sub arrays is shuffled, without duplicates, in far far less code.
$bingoNumbers = array(
"rij_1" => array(10,11,12,13,14,15,16,17,18,19),
"rij_2" => array(20,21,22,23,24,25,26,27,28,29),
"rij_3" => array(30,31,32,33,34,35,36,37,38,39),
"rij_4" => array(40,41,42,43,44,45,46,47,48,49),
"rij_5" => array(50,51,52,53,54,55,56,57,58,59),
"rij_6" => array(60,61,62,63,64,65,66,67,68,69)
);
foreach(array_keys($bingoNumbers) as $key)
shuffle($bingoNumbers[$key]);
echo "<table border='1'>";
foreach($bingoNumbers as $v)
echo "<tr><td>" . implode("</td><td>", $v) . "</td></tr>";
echo "</table>";
Demo
If you only want a 6x6 grid, just array_slice() your sub arrays, e.g.
$bingoNumbers = array(
"rij_1" => array(10,11,12,13,14,15,16,17,18,19),
"rij_2" => array(20,21,22,23,24,25,26,27,28,29),
"rij_3" => array(30,31,32,33,34,35,36,37,38,39),
"rij_4" => array(40,41,42,43,44,45,46,47,48,49),
"rij_5" => array(50,51,52,53,54,55,56,57,58,59),
"rij_6" => array(60,61,62,63,64,65,66,67,68,69)
);
foreach(array_keys($bingoNumbers) as $key)
shuffle($bingoNumbers[$key]);
echo "<table border='1'>";
foreach($bingoNumbers as $v)
echo "<tr><td>" . implode("</td><td>", array_slice($v, 0, 6)) . "</td></tr>";
//^^^^^^^^^^^^ Just slice your sub array
echo "</table>";
Demo

Related

mysqli_fetch_array using a foreach loop

Ive got a pretty basic table named 'customers' with four columns:
ID (primary Auto Increment)
businessName
contactName
contactEmail
I call it with:
$result = mysqli_query($con, "SELECT * FROM customers");
and was using mysqli_fetch_array to display it on the page with a foreach loop:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
Which gives you an array like:
Array ( [id] => 1 [businessName] => Microsoft [contactName] => Bill Gates [contactEmail] => bill#microsoft.com ) Array ( [id] => 2 [businessName] => Amazon [contactName] => Jeff Bezos [contactEmail] => jeff#amazon.com )
Is it possible to display results differently based on which column (technically now position in the array) they are in? I would like to make a
a href="mailto:bill#microsoft.com"
link when it gets to contactEmail.
What if I wanted to display just one key or value instead of using foreach?
It doesn't seem possible to call
$row['contactEmail']
in the foreach loop
which confuses me since below that I am able to create a link to
$row['id']
If anyone has any ideas how to do this, or if there is a better way to be displaying this information, I'm open to suggestions, as I'm not very good at programming, especially PHP.
Yes! you can just add like this:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
foreach ($row as $key => $value) {
if($key == "contactEmail"){
$mailUrl = "mailto:".$value;
echo "<td>".$value."";
}
else{
echo "<td>" . $value . "</td>";
}
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
Yes, You can able to mysqli_fetch_array retrieve data directly using foreach loop. like bellow :
<?php
$result = mysqli_query($con, "SELECT * FROM customers");
?>
<table>
<tr>
<td>Business Name</td>
<td>Contact Name</td>
<td>#</td>
</tr>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>".$row['businessName']."</td>";
foreach ($row as $key => $value) {
$newValue = $key == "contactEmail" ? ''.$value.'' : $value;
echo "<td>" . $newValue . "</td>";
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
?>
</table>

PHP Associative Array To Table

I am trying to sort an associative array in ascending in order and then transfer it to a HTML table and I am currently stumped at an error. I looked for guidelines here on SO and followed instructions on some posts:
PHP display associative array in HTML table
But still no luck, here is my attempt:
<?php
function format($g){
array_multisort($g, SORT_ASC);
echo "<table>";
foreach($g as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>" . $row2 . "</td>";
}
echo "</tr>";
}
echo "</table>";
}
$bib = array("Luke"=>"10",
"John"=>"30",
"Matt"=>"20",
"Mark"=>"40");
format($bib);
?>
My debugger is telling me there is an error at my for each loop but I don't see how it is wrong unless there is some syntax error that I am not seeing? The error is saying Invalid argument supplied for foreach()
Because your $bib is only single array but you use two foreach to loop this array
At 2nd loop, your $row variable is a string, you can't use foreach for this type
Can you try that for single array ?
<?php
function format($data) {
array_multisort($data, SORT_ASC);
echo "<table>";
foreach($data as $k => $v) {
echo "<tr>";
echo "<td>$k</td>";
echo "<td>$v</td>";
echo "</tr>";
}
echo "</table>";
}
$bib = array("Luke"=>"10",
"John"=>"30",
"Matt"=>"20",
"Mark"=>"40");
format($bib);
?>
$k is Luke John Matt and Mark,
$v is 10 30 20 and 40
You can see the foreach example here: http://php.net/manual/en/control-structures.foreach.php
Hope this helpful ^^
You can try this
<?php
function format($data){
array_multisort($data, SORT_ASC);
echo "<table>";
foreach($data as $key => $row) {
echo "<tr>";
echo "<td>" . $key . "</td>";
echo "<td>" . $row . "</td>";
echo "</tr>";
}
echo "</table>";
}
$bib = array(
"Luke"=>"10",
"John"=>"30",
"Matt"=>"20",
"Mark"=>"40"
);
format($bib);
?>

how to take foreach result in a table format

I want to take the result of foreach in a table format and that whole table in a variable.
Here is my model:
public function cron_job_seller(){
$this->db->select('*');
$this->db->from('wc_seller_products');
$query = $this->db->get();
$result = array();
foreach ($query->result() as $row){
$result[] = $row;
}
return $result;
}
and my controller is
public function cron_job(){
$this->load->model('home/Home_model');
$buyer = $this->Home_model->cron_job_buyer();
$this->load->library('email', array('mailtype'=>'html'));
$seller = $this->Home_model->cron_job_seller();
echo "<table>";
foreach($seller as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>" . $row2 . "</td>";
}
echo "</tr>";
}
echo "</table>";
gives o/p like this in table format
19 102 Rolex 65 Good 0000-00-00 fh ghf fgh ghf ghf gfh ghf ghf 56 56 download14.jpg 11/6/2016 19:03 2016-07-15 12:13:35 1 0
when i print $seller variable it gives
Array ( [0] => stdClass Object ( [id] => 19 [seller_id] => 102 [brand_name] => Rolex [model_no] => 65 [condition] => Good [date_purchase] => 0000-00-00 [case_size] => fh [case_shape] => ghf [case_material] => fgh [strap_type] => ghf [dial_colour] => ghf [water_resistance] => gfh [local_overseas] => ghf [warranty_period] => ghf [min_price] => 56 [sale_price] => 56 [photo] => download14.jpg [date] => 11/6/2016 19:03 [time] => 2016-07-15 12:13:35 [status] => 1 [login] => 0 [verified] => )
now i want 2 things in this:
1. that whole table in a single variable.
2. array keys like id, seller_id,brand_name as table heading
i really got confused what to do now and how to do...please help
public function cron_job() {
$this->load->model('home/Home_model');
$buyer = $this->Home_model->cron_job_buyer();
$this->load->library('email', array('mailtype'=>'html'));
$seller = $this->Home_model->cron_job_seller();
$theader = '';
$tbody = "<tbody>";
foreach($seller as $key => $row) {
$tbody .= "<tr>";
foreach($row as $key2 => $row2){
if (!$theader) {
$theader = array_keys($row2);
}
$tbody .= "<td>" . $row2 . "</td>";
}
$tbody .= "</tr>";
}
$tbody .= "</tbody>";
if (!empty($theader)) {
$theader = '<thead><th>' . implode('</th><th>', $theader) . '</th></thead>';
}
$table = '<table>'.$theader.$tbody.'</table>';
}
you don't need to worry much about it... It could be a solution. Just do like this in your controller:
$seller = $this->Home_model->cron_job_seller();
$table = "<table border='1'>";
$i=1;
foreach($seller as $key=>$row) { //you don't need to loop twice
if($i == 1){
$table.="<tr>";
$table .= "<th>".$key."</th>";
$table.="</tr>";
$i=0; //change value of $i so for next iteration the header will not print
}
$table .= "<tr>";
$table .= "<td>" . $row . "</td>";
$table.= "</tr>";
}
$table .= "</table>";
and also you need to return $query->result() from your model.
and now try print $table
using echo $table; it will print result as you want and now it is also set in a single variable so you can, and you set to $data['table'] = $table and end it to view, if you need.
You can just loop through the Array of Data from the DB and since each row is an array of Standard PHP Object (which contains the column names as keys), you can then extract the Column Names from the first row and then use it to construct the Table Header. Afterwards, you can just continue building Rows containing the actual Data you want. The Code below illustrates how:
<?php
function cron_job() {
$strOutput = "<table class='cron-tbl'>";
$this->load->model('home/Home_model');
$buyer = $this->Home_model->cron_job_buyer();
$this->load->library('email', array('mailtype' => 'html'));
$seller = $this->Home_model->cron_job_seller();
$cue = 0;
foreach ($seller as $key => $row) {
if($cue == 0){
// CREATE THE HEADER ROW:
$strOutput .= "<tr class='cron-head-row'>" . PHP_EOL;
foreach($row as $rowName=>$rowVal){
$strOutput .= "<th class='cron-head-cell'>{$rowName}</th>" . PHP_EOL;
}
$strOutput .= "</tr>" . PHP_EOL;
$strOutput .= "<tbody class='cron-body'>" . PHP_EOL;
}
// CREATE THE TABLE-BODY CELL
$strOutput .= "</tr>" . PHP_EOL;
foreach ($row as $rowKey => $data) {
$strOutput .= "<td class='cron-data-cell'>{$data}</td>" . PHP_EOL;
}
$strOutput .= "</tr>" . PHP_EOL;
$cue++;
}
$strOutput .= "</tbody>" . PHP_EOL;
$strOutput .= "</table>" . PHP_EOL;;
return $strOutput;
}
echo (cron_job());
Cheers & Good Luck...
Test it out yourself HERE.
You are doing correct but need some modifications
What you need to do is in you second foreach() loop you need to convert your object to array and take out the array keys array_keys($array) in a variable and print this keys to variable. As shown bellow.
$table = "<table border='1'>";
foreach($seller as $key=>$row) { //you don't need to loop twice
$table .="<tr>";
// creating a table heading
if($key === 0 ){
$cols = array_keys((array)$row); // Convert the object to array and take out all keys of array and assign to $cols variable
$table .="<th>".implode("</th><th>", $cols);
$table .="</th></tr><tr>";
}
// table heading end
$table .= '<td>'. implode('</td><td>', (array)$row). '</td>';
$table .= "</tr>";
}
$table .="</table>";
echo $table;
Try this way.
I guess html tag, body tag are missing. That's why didnot display table the way you want.
My suggestion is that for html part, it is better if put in view.
I have create view page cron_job_seller.php with bootstrap.
// Model - Change to this
public function cron_job_seller()
{
$this->db->select('*');
$this->db->from('wc_seller_products');
return $this->db->get();
}
// Controller
public function cron_job() {
$this->load->model('home/Home_model');
$this->load->library('email', array('mailtype'=>'html'));
$buyer = $this->Home_model->cron_job_buyer();
$seller = $this->Home_model->cron_job_seller();
$data['seller'] = $seller // Send data to View
// Create cron_job_seller.php file in Views Folder.
$this->load->view('cron_job_seller', $data);
}
// View cron_job_seller.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sample Table</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<?php foreach($seller->result() as $row) { ?>
<tr>
<td><?php echo $row->colname_1; ?></td>
<td><?php echo $row->colname_2; ?></td>
<td><?php echo $row->colname_3; ?></td>
<td><?php echo $row->colname_4; ?></td>
</tr>
<?php } ?>
</table>
</div>
</body>
</html>

convert php sql Result from Vertical to Horizontal

The following code generate the result(one record) in a vertical table is there any way to convert to horizontal like with a nice styling.. in addition if possible to get certain column in a popup window using the parameter in the query, using jquery or CSS
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<?
$table = $_GET["table"];
$lon = $_GET["lon"];
$lat = $_GET["lat"];
$sql = "select
st_geometrytype(geom) as geometrytype,
st_area(geom) as area, *
from $table
where
st_contains(
geom,
st_transform(
st_setsrid(
st_makepoint($lon, $lat),
4326),
2276))";
$db = pg_connect("dbname=db user=user password=pass");
$result = pg_query($db, $sql);
while( $row = pg_fetch_assoc($result) )
{
print "<table>";
foreach ( array_keys($row) as $column_name )
{
if ( $column_name <> "geom" )
{
print "<tr>";
print "<th>" . $column_name . "</th>";
print "<td>" . $row[$column_name] . "</td>";
print "</tr>";
}
}
print "</table>";
}
?>
</body>
</html>
so far I am using this CSS to style my table.
th
{
text-align:right;
padding-right:0.5em;
}
td
{
text-align:center;
}
many thanks..
Your are printing the tr at the same time the loop runs, so it will make trs and obviously it will be vertical, to make it horizontal , your loop will be like this;
while( $row = pg_fetch_assoc($result) )
{
print "<table>";
print "<tr>";
foreach ( array_keys($row) as $column )
{
if ( $column_name <> "geom" )
{
print "<th>" . $column . "</th>";
}
}
print "</tr>";
print "<tr>"; <-- this one here opening tag
foreach ( array_keys($row) as $column_name )
{
if ( $column_name <> "geom" )
{
print "<td>" . $row[$column_name] . "</td>";
}
}
print "</tr>"; <-- this one here closing tag
print "</table>";
}
code for display 8 elements horizontally.
<table>
<?if($c==8){echo "<tr >";$c=0; }<td> ?>
// your elements
<? echo "</td>";
$c++;?>
</tr>
</table>

Every 8th instance go to new tr

I am building a calender in PHP.
In the controller, I have detected the amount of days in a given month, and set that range into an array: daysInMonthArray.
In the view, I then foreach this array outputting each number into a <td>:
<tr>
<?php
// output the number of days in the month
foreach($this->daysInMonthArray as $days1){
foreach($days1 as $key => $object){
echo "<td>" . $object . "</td>";
}
} ?>
</tr>
I would like to start a new <tr> every 8th number, as there are 7 days in a week and need to start a new row to begin a new week.
I have tried enclosing an if statement that detected the remainder of the output if divided by 8. if the output was 0 then new line, if not then carry on. However, this didnt work because the <tr> tags are outside the php statement.
Following answers and comments I have updated my code to:
<tr>
<?php
// output the number of days in the month
foreach($this->daysInMonthArray as $days1){
foreach($days1 as $key => $object){
if($object % 8 == 0){
echo "</tr><tr><td>" . $object . "</td>";
}else {
echo "<td>" . $object . "</td>";
}
}
} ?>
</tr>
This very nearly works, except for the middle two weeks in a month. It puts 8 days in the middle 2 weeks but 7 on the first and last week.
You've pretty much answered this one yourself with the following:
this didnt work because the tags are outside the php statement
You have to get the <tr> tags inside the loop.
<?php
$daysInRow = 0;
// output the number of days in the month
foreach($this->daysInMonthArray as $days1)
{
foreach($days1 as $key => $object)
{
if($daysInRow % 7 === 0)
{
echo '<tr>';
}
echo "<td>" . $object . "</td>";
if($daysInRow % 7 === 0)
{
echo '</tr>';
}
if($daysInRow % 7 === 0)
{
$daysInRow = 0;
}
else
{
$daysInRow++;
}
}
}
?>
This is untested code and could be more concise but hopefully you get the idea.
One prob that you're gonna run into is that you're nesting your table in an existing table. Try:
<tr><td>
<?php
// output the number of days in the month
foreach($this->daysInMonthArray as $days1){
echo "<table>";
$dayofweek = 0;
foreach($days1 as $key => $object){
if($dayofweek%7 == 0)
echo "<tr>";
echo "<td>" . $object . "</td>";
if($dayofweek%7 == 0)
echo "</tr>";
$dayofweek++;
}
if($dayofweek%7 != 0) //last tr
echo "</tr>";
echo "</table>";
}
?>
</td></tr>

Categories