Pulling specific random values from php array - php

On the page I'm creating there is graphic representation of pigeon-holes with five compartments for new comments. If there is new unread comment it should show up as graphic in one random compartment. But it won't happen if all of the 5 are
already occupied. So if someone writes new comment I like the code to check for if there is already five of them taken, and if not, than to randomly occupied one of the remaining ones. So "new_c" stands for number of
unread (new) comments, and c1-c5 stands for compartments. Value 0 means empty compartment for each "c". I was trying to make code that would first separate new_c from rest of the array after knowing the number is smaller than 5,
so I'm only working with 5 compartments. And than to determine which one is/are empty. And then randomly choose one empty to occupy. It's not really working as it is I probably am not using that array_keys properly as c2 is changed to some other value than 0 but still is being echoed, there is probably also a better/more efficient way to achieve that. I will really appreciate some input.
<?php
$tucQuery = "SELECT new_c,c1,c2,c3,c4,c5 FROM users WHERE id = '{$author_id}' LIMIT 1";
$result_tuc = mysqli_query($connection, $tucQuery);
$tucArray = mysqli_fetch_assoc($result_tuc);
mysqli_free_result($result_tuc);
$new_c = $tucArray[0];
if($new_c < 5){
$new_array = array_keys((array_slice($tucArray,1)), 0);
$rand_zero = array_rand($new_array, 1);
echo $rand_zero + 1;
}
?>
Bellow code works but it doesn't seem to be efficient and there is probably a better way.
if($new_c < 5){
$empties = array();
if($tucArray['c1'] == 0){
$empties[] = 1;
}
if($tucArray['c2'] == 0){
$empties[] = 2;
}
if($tucArray['c3'] == 0){
$empties[] = 3;
}
if($tucArray['c4'] == 0){
$empties[] = 4;
}
if($tucArray['c5'] == 0){
$empties[] = 5;
}
print_r($empties);
$rand_zero = array_rand((array_flip($empties)), 1);
echo $rand_zero;
}

Related

Sorting Steam Web Api GetPlayerSummaries response

I'm making class which will get data about teams - 5 Steam users basing on 32bit SteamIDs stored in database for each team. It's translated then to 64bit SteamID.
I need response in correct order, because there is specified captain of the team.
And here's the problem - GetPlayerSummaries always returns profiles in random order. I want these to be sorted like in url.
I've tried already sort() methods, but it seems not working, like I want to.
I've tried matching 'steamid' with this translated 64 bit SteamID like this:
$profile_get = json_decode(file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=mywebapikey&steamids='.$stmid64['capt'].','.$stmid64['p2'].','.$stmid64['p3'].','.$stmid64['p4'].','.$stmid64['p5']),true);
$profile_get = $profile_get['response'];
foreach($profile_get['players'] as $profile){
if($profile['steamid'] === $stmid64['capt']){
$profile_got = array(
0 => $profile
);
}
elseif($profile['steamid'] === $stmid64['p2']){
$profile_got[1] = $profile;
}
elseif($profile['steamid'] === $stmid64['p3']){
$profile_got[2] = $profile;
}
elseif($profile['steamid'] === $stmid64['p4']){
$profile_got[3] = $profile;
}
elseif($profile['steamid'] === $stmid64['p5']){
$profile_got[4] = $profile;
}
}
where $stmid64 is 64bit SteamID, but it obviously don't work :(
var_dump($profile_got[0]);
var_dump($profile_got[1]);
var_dump($profile_got[2]);
var_dump($profile_got[3]);
var_dump($profile_got[4]);
and var_dump($profile_got); returns NULL.
I've tried many different codes, but they didn't work also.
I hope you can help me with not doing all requests separately.
$profile_get = json_decode(file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.$mywebapikey.'&steamids='.$stmid64['capt'].','.$stmid64['p2'].','.$stmid64['p3'].','.$stmid64['p4'].','.$stmid64['p5']),true);
for ($i = 0; $i < 5; $i++) {
if ($i == 0)
$player = 'capt';
else
$player = 'p'.($i+1);
for ($j = 0; $j < 5; $j++) {
if ($stmid64[$player] == $profile_get['response']['players'][$j]['steamid']) {
$profile_got[$i] = $profile_get['response']['players'][$j];
break;
}
}
}
var_dump($profile_got[0]);
var_dump($profile_got[1]);
var_dump($profile_got[2]);
var_dump($profile_got[3]);
var_dump($profile_got[4]);
cheers
this will work as intended, it will order your array by 'capt' (why not p1 instead ? , you could save 3 lines), 'p2', 'p3', 'p4', 'p5'. you can still extend this in many ways but basically this is how to put them in the right order. also mind that i stored your (well mine) api key inside a $var

php "count()" function and DB

I have a Joomla 1.5 site. I have articles in my site with different "status". What I'm trying to do is "count" and show how many articles have for example "status = 1"(expired) or "status = 3"(blocked) or "status = 2"(active) etc..
Here is the statuses in PhpMyAdmin - http://awesomescreenshot.com/07a8ijz75
Here is what I wrote, but it ALWAYS gives me same result - 1
<?php echo count($this->row->status==1) ?>
Did I miss something?
Thanks
Use the SQL count function.
select count(*) from articles where status = 1;
Use your DB! If you are sorting, counting, etc, data from a database in PHP code you're doing it wrong.
If you want all statuses, do something like:
select status, count(*) from articles group by status;
The count function in PHP counts all the elements in an array, and in your example you passed it a boolean value. As a result count doesn't know what to do with it, and so it returns -1, which isn't a valid count.
My PHP is really rusty (I haven't used it in a looong time), but here are two possible ways to accomplish what you want:
1. Use a function map/reduce style
<?php
$row[0]->status = 1;
$row[1]->status = 2;
$row[2]->status = 1;
$row[3]->status = 3;
$row[4]->status = 1;
// Count the number of statuses that are equal to 1
echo array_reduce(array_map(function($x) {
return $x->status == 1 ? 1: 0;
}, $row), function($x, $y) {return $x + $y;});
You'll have to replace the $row variable with $this->row, obviously. The code is essentially working in two steps. The inner part:
array_map(function($x) {
return $x->status == 1 ? 1: 0;
}, $row)
Creates a list where every status that's equal to 1 becomes a 1 and everything else becomes a 0. So you have an array of "array(1, 0, 1, 0, 1)". The out part of the code:
array_reduce( ... , function($x, $y) {return $x + $y;});
Takes the new array as the first argument and sums it all up by passing in the first two values of the array into the function, and then each following value and the result of the last function call. As a result all the values get summed, and you have a proper count of the matching values.
2. Use a simple procedural style
<?php
$row[0]->status = 1;
$row[1]->status = 2;
$row[2]->status = 1;
$row[3]->status = 3;
$row[4]->status = 1;
// Do it again, but in a procedural style
$num_1_statuses = 0;
foreach ($row as $r) {
if ($r->status == 1) {
$num_1_statuses++;
}
}
echo $num_1_statuses;
This should be really straightforward, it just has a variable that gets incremented whenever a row's status matches.

php sql find and insert in empty slot

I have a game script thing set up, and when it creates a new character I want it to find an empty address for that players house.
The two relevant table fields it inserts are 'city' and 'number'. The 'city' is a random number out of 10, and the 'number' can be 1-250.
What it needs to do though is make sure there's not already an entry with the 2 random numbers it finds in the 'HOUSES' table, and if there is, then change the numbers. Repeat until it finds an 'address' not in use, then insert it.
I have a method set up to do this, but I know it's shoddy- there's probably some more logical and easier way. Any ideas?
UPDATE
Here's my current code:
$found = 0;
while ($found == 0) {
$num = (rand()%250)+1; $city = (rand()%10)+1;
$sql_result2 = mysql_query("SELECT * FROM houses WHERE city='$city' AND number='$num'", $db);
if (mysql_num_rows($sql_result2) == 0) { $found = 1; }
}
You can either do this in PHP as you do or by using a MySQL trigger.
If you stick to the PHP way, then instead of generating a number every time, do something like this
$found = 0;
$cityarr = array();
$numberarr = array();
//create the cityarr
for($i=1; $i<=10;$i++)
$cityarr[] = i;
//create the numberarr
for($i=1; $i<=250;$i++)
$numberarr[] = i;
//shuffle the arrays
shuffle($cityarr);
shuffle($numberarr);
//iterate until you find n unused one
foreach($cityarr as $city) {
foreach($numberarr as $num) {
$sql_result2 = mysql_query("SELECT * FROM houses
WHERE city='$city' AND number='$num'", $db);
if (mysql_num_rows($sql_result2) == 0) {
$found = 1;
break;
}
}
if($found) break;
}
this way you don't check the same value more than once, and you still check randomly.
But you should really consider fetching all your records before the loops, so you only have one query. That would also increase the performance a lot.
like
$taken = array();
for($i=1; $i<=10;$i++)
$taken[i] = array();
$records = mysql_query("SELECT * FROM houses", $db);
while($rec = mysql_fetch_assoc($records)) {
$taken[$rec['city']][] = $rec['number'];
}
for($i=1; $i<=10;$i++)
$cityarr[] = i;
for($i=1; $i<=250;$i++)
$numberarr[] = i;
foreach($cityarr as $city) {
foreach($numberarr as $num) {
if(in_array($num, $taken[]) {
$cityNotTaken = $city;
$numberNotTaken = $number;
$found = 1;
break;
}
}
if($found) break;
}
echo 'City ' . $cityNotTaken . ' number ' . $numberNotTaken . ' is not taken!';
I would go with this method :-)
Doing it the way you say can cause problems when there is only a couple (or even 1 left). It could take ages for the script to find an empty house.
What I recommend doing is insert all 2500 records in the database (combo 1-10 with 1-250) and mark with it if it's empty or not (or create a combo table with user <> house) and match it on that.
With MySQL you can select a random entry from the database witch is empty within no-time!
Because it's only 2500 records, you can do ORDER BY RAND() LIMIT 1 to get a random row. I don't recommend this when you have much more records.

SQL Result Random loop through

I have a SQL database that contains a field. I can get all of the elements in that field by:
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$ftype =$row['ftype']; //name of field is 'ftype'
print $ftype} //do something
I want a random element to be printed out each time the page is opened/refreshed.
Knowing that the result is an array containing the information i want, I want to randomly choose an element of the array. Also, if there are N elements in the array, I want to choose all N elements exactly once before I show any element again for second time. The process repeats itself. I know how to code something like this in java or python, but I don't think that's the way I should go.
I think I need to use javascript, but I'm just not sure what technology to use.
UPDATE:
Patrick's idea seems to be exactly what i was looking for. I thought I would share what I have now and maybe you can suggest optimization. I hope the intent in the code is obvious.
<?
session_start();
if (!isset($_SESSION['count']) || !isset($_SESSION['randomArray'])) {
$count = 0;
$randomArray = array();
$sql="SELECT youtubeurl FROM Foodlist";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
array_push($randomArray,$row['youtubeurl']);
}
shuffle($randomArray);
$_SESSION['randomArray'] = $randomArray;
$_SESSION['count'] = $count;
} elseif ($_SESSION['count'] >= sizeof($_SESSION['randomArray'])){
$_SESSION['count'] = 0;
$randomArray = $_SESSION['randomArray'];
shuffle($randomArray);
$_SESSION['randomArray'] = $randomArray;
} else{
$randomArray = $_SESSION['randomArray'];
$count = $_SESSION['count'];
echo $randomArray[$count];
$_SESSION['count']++;
}
?>
You can do this without Javascript, however you'll need to open/maintain a session.
Pseudocode:
data = data_from_mysql()
choice = random.choice(data, exclude = SESSION['choices'])
SESSION['choices'].append(choice)
print choice
if len(SESSION['choices']) == len(data):
SESSION['choices'] = []
If you want a random result let the dbms take care of it. Add this to the bottom of your sql query.
ORDER BY RAND()
LIMIT 1

php - calculate price multiplied by quantity for several items to get individual totals and a grand total

I have a form that has 7 different items. The user will be able to input quantity (unlimited) and the price will be set for each item (let's say for example, item 1 is $18, and item 2 is $20, etc.). What I have done with another form that's almost identical is this:
if(!empty($_POST[qty_item_1])) {
$total_1 = ($_POST[qty_item_1] * 18);
} else {
$total_1 = "0";
}
if(!empty($_POST[qty_item_2])) {
$total_2 = ($_POST[qty_item_2] * 20);
} else {
$total_2 = "0";
}
I would have a code block like those for each item. It seems to work fine but I feel like this is probably the hard way to do it but I'm having trouble figuring out what else I might do. Any suggestions?
Given your field names, you could do something like:
$totals = array();
for ($i = 1; $i <= 7; $i++) {
$total[$i] = isset($_POST["qty_item_{$i}"]) ? intval($_POST["qty_item_{$i}"]) : 0;
}
The other option is to simply name your fields qty_item[]. When PHP parses the submitted data, it'll convert all those qty_item fields into an array for you. You'd still need to post-process to make sure that they contain valid numbers and whatnot, thoguh.

Categories