I have a for loop like so:
for((int) $i = 0; $i < $number_of_updates; $i++)
{
//query here
$result = mysql_query($query);
list($name) = mysql_fetch_row($result);
$points = 1;
//some functions to execute here... and then
//store results in session to show on other page
$output = $points.' times '.$name;
$_SESSION['item'][] = $output;
}
And then I show my results on view page like so:
foreach (array_unique($_SESSION['item']) as $output)
{
echo ('<p>'.$output.'</p>');
}
It echoes my results out of the loop like so:
1 times foo
1 times foo
1 times bar
1 times foo
etc...
Now the question. How do I sum those results up so they don't duplicate? Instead they are shown like so:
3 times foo
1 times bar
User array_count_values
for(/*(int) <- this is not neccessary (c++ background?) */ $i = 0; $i < $number_of_updates; $i++)
{
// your code
$_SESSION['item'][] = $name;
}
foreach(array_count_values($_SESSION['item']) as $name => $times)
echo ('<p>'.$times.' times '.$name.'</p>');
Of course counting the values directly is more memory and time efficient. This version is only neccessary if you somehow need to preserve the order of the elements.
Why didn't you store in your array directly the sum?
for((int) $i = 0; $i < $number_of_updates; $i++)
{
//query here
$result = mysql_query($query);
list($name) = mysql_fetch_row($result);
$points = 1;
//some functions to execute here... and then
//store results in session to show on other page
$_SESSION['item'][$name] +=$points;
}
Try this:
for((int) $i = 0; $i < $number_of_updates; $i++)
{
//query here
$result = mysql_query($query);
list($name) = mysql_fetch_row($result);
$points = 1;
//some functions to execute here... and then
//store results in session to show on other page
//$output = $points.' times '.$name;
//$_SESSION['item'][] = $output;
if( isset( $_SESSION['count'][$name] )){
$prev = $_SESSION['count'][$name];
}else{
$prev = 0;
}
$_SESSION['count'][$name] = $points + $prev ;
}
print_r( $_SESSION['count'] );
Related
I am trying to make card game.
I have 6 variable that are stored in array. Than I use fisherYates method to randomize array, and display four of them.
Problem is, when I randomize it this way only, it will give only random output of those six, with all different types.
So I want that some repeats like, if you draw four cards, you get output of
ex: club, club, diamond,heart, or heart, star,star,heart.. if you get a point..
I thought to do it like this way: put the array in loop of 4 times, and every time it loops, it stores first, or last value in new array, so that way, I can have greater chances of combination of same cards in output array.
But I'm stuck, and I don't know how to do it :/
this is what I've tried so far
$diamond = 'cube.jpg';
$heart = 'heart.jpg';
$spade = 'spade.jpg';
$club = 'tref.jpg';
$star='star.jpg';
$qmark='qmark.jpg';
$time=microtime(35);
$arr=[$diamond,$heart,$spade,$club,$star,$qmark];
function fisherYatesShuffle(&$items, $time)
{
for ($i = count($items) - 1; $i > 0; $i--)
{
$j = #mt_rand(0, $i);
$tmp = $items[$i];
$items[$i] = $items[$j];
$items[$j] = $tmp;
}
return $items;
}
$i=0;
do {
$niz[$i]=fisherYatesShuffle($arr,$time);
reset($niz);
$i++;
} while ($i <= 3);
Got a solution. Was just to simply do foreach of first element of multidimensional array :)
Code goes like this:
$diamond = 'cube.jpg';
$heart = 'heart.jpg';
$spade = 'spade.jpg';
$club = 'tref.jpg';
$star='star.jpg';
$qmark='qmark.jpg';
$time=microtime(35);
$arr=[$diamond,$heart,$spade,$club,$star,$qmark];
$niz=array();
$i=0;
do {
$niz[$i]=fisherYatesShuffle($arr,$time);
//reset($niz);
$i++;
} while ($i <= 3);
foreach ($niz as $key ) {
$randomArr[]=$key[0]; ;
}
function fisherYatesShuffle(&$items, $time)
{
for ($i = count($items) - 1; $i > 0; $i--)
{
$j = #mt_rand(0, $i);
$tmp = $items[$i];
$items[$i] = $items[$j];
$items[$j] = $tmp;
}
return $items;
}
print_r($randomArr);
I want to distribute an item to specific pieces without cutting the excess piece,
example:
$persons = 7;
$rooms = 2;
for($i = 0; $i < $rooms; $i++)
{
//distribute the persons per room
}
//the endpoint should be
$the_room[0] = 4 //instead of 3.5
$the_room[1] = 3 //instead of 3.5
How about an approach that first equally distributes pieces, then randomises the remainder?
$persons = 7;
$rooms = 2;
$the_room = array();
for($i = 0; $i < $rooms; $i++)
{
$the_room[$i] = floor($persons / $rooms);
}
// Random Distribution
while( $persons - array_sum($the_room) > 0)
{
$the_room[array_rand($the_room)]++;
}
// Sequential Distribution
// $index = 0;
// while( $persons - array_sum($the_room) > 0)
// {
// $the_room[$index++]++;
// }
print_r($the_room);
Need to receive data of fields from $i raw of mysqli object.
$res = $mysqli->query("SELECT mood,count(mood) as number FROM em_mood GROUP by mood ORDER by mood ASC");
$obj = $res->fetch_object();
for ($i = 1; $i <= 10; $i++){
if ($i==$obj->mood[$i]) $mood_result .= "<div class='chart'>".$obj->mood[$i].$obj->number[$i]."</div>";
else $mood_result .= "<div class='chart'>empty</div>";
}
Explanation:
$obj->mood is equal from 1 to 10.
if $obj->mood is missing "2" for example, I need to exchange it with empty div.
In other words, what is the syntax of getting field [mood] value in lets say second raw? something like $obj[2][mood]?
Update:
Looks like it works like this:
for ($i = 1; $i <= 10; $i++){
$res = $mysqli->query("SELECT mood,count(mood) as number FROM em_mood WHERE date>=CURDATE()-INTERVAL 30 DAY and mood=".$i);
$obj = $res->fetch_object();
echo $obj->mood." - ".$obj->number."<br>";
}
Is there any way to make this more simple? To don`t make 10 mysqli queries?
$raw = [];
$sql = "SELECT mood,count(mood) as number FROM em_mood GROUP by mood";
$res = $mysqli->query($sql);
while ($obj = $res->fetch_object())
{
$raw[$obj->mood] = $obj->number;
}
now you will have your "raw" data all right
for ($i = 1; $i <= 10; $i++){
if (isset($raw[$i])) {
$mood_result .= "<div class='chart'>$i - $raw[$i]</div>";
} else {
$mood_result .= "<div class='chart'>empty</div>";
}
}
How can I select a random set of rows
The important bits:
I need to specify the number of random rows to select via a variable.
Say for instance the number of rows I want to select is 10, then it HAS TO select 10 DIFFERENT rows. I don't want it to pick out the same row a few times until it has 10.
The code below picks out 1 random row, how can I tailor this to the above spec?
<?php $rows = get_field('repeater_field_name');
$row_count = count($rows);
$i = rand(0, $row_count - 1);
echo $rows[$i]['sub_field_name']; ?>
<?php
$rows = get_field('repeater_field_name');
$row_count = count($rows);
$rand_rows = array();
for ($i = 0; $i < min($row_count, 10); $i++) {
// Find an index we haven't used already (FYI - this will not scale
// well for large $row_count...)
$r = rand(0, $row_count - 1);
while (array_search($r, $rand_rows) !== false) {
$r = rand(0, $row_count - 1);
}
$rand_rows[] = $r;
echo $rows[$r]['sub_field_name'];
}
?>
This is a better implementation:
<?
$rows_i_want = 10;
$rows = get_field('repeater_field_name');
// Pull out 10 random rows
$rand = array_rand($rows, min(count($rows), $rows_i_want));
// Shuffle the array
shuffle($rand);
foreach ($rand as $row) {
echo $rows[$row]['sub_field_name'];
}
?>
Simply loop through the random row process the number of random rows you want to get.
<?php
$rows_to_get=10;
$rows = get_field('repeater_field_name');
$row_count = count($rows);
$x=0
while($x<$rows_to_get){
echo $rows[rand(0, $row_count - 1)]['sub_field_name'];
$x++;
}
?>
You can give this a try
$rows = get_field('repeater_field_name');
var_dump(__myRand($rows, 10));
function __myRand($rows, $total = 1) {
$rowCount = count($rows);
$output = array();
$x = 0;
$i = mt_rand(0, $rowCount - 1);
while ( $x < $total ) {
if (array_key_exists($i, $output)) {
$i = mt_rand(0, $rowCount - 1);
} else {
$output[$i] = $rows[$i]['sub_field_name'];
$x ++;
}
}
return $output ;
}
A simple solution :
$rows = get_field('repeater_field_name');
$limit = 10;
// build new array
$data = array();
foreach ($rows as $r) { $data[] = $r['sub_field_name']; }
shuffle($data);
$data = array_slice($data, 0, min(count($data), $limit));
foreach ($data as $val) {
// do what you want
echo $val;
}
$result = mysql_query($query);
$filter = array();
while($r = mysql_fetch_array($result))
{
for ( $i = 0; $i<20; $i++)
{
$filter[] = $r["name"][$i];
}
$name = implode(",", $filter);
}
Above is a portion of main code. I want to restrict loop to run only 20 times. if above 20 it should omit...but this gives me some odd result...I know some where I made a mistake but where?
mysql_fetch_array only fetches a single row of data from the query results. It looks like you're trying to fetch only a single field from the results, so you'd want something like this:
$i = 0;
while($row = $mysql_fetch_assoc($result)) {
$i++
if ($i >= 20) {
break;
}
$filter[] = $row['name'];
}
$name = implode(",", $filter);
But this is very inefficient. Why not have MySQL do the row-limiting itself?
SELECT your,fields,here
FROM yourtable
WHERE ...
ORDER BY ...
LIMIT 20
and then you only get 20 rows to start with, without forcing mysql to fetch all however-many-there-are-beyond-20.
You are not advancing to the next row
$result = mysql_query($query);
$filter = array();
$i = 0;
while($r = mysql_fetch_array($result))
{
$filter[] = $r["name"][$i]; }
$name = implode(",", $filter);
if(++$i == 20)
{
break;
}
}