php array trouble - php

I'm a rookie with php arrays, and have a problem. I downloaded a blackjack PHP script, it stores the current players hand, deck, and dealers hand in THE $_POST, which isn't good.
So I'm trying to alter it to store them in a database instead. I'm getting errors and this is the code I'm playing with. The original code for drawing a random card from the deck is this:
shuffle($deck);
for ($i = 0; $i < 2; $i++) {
$hand[] = array_shift($deck);
$dealer[] = array_shift($deck);
}
$handstr = serialize($hand);
$deckstr= serialize($deck);
$dealerstr= serialize($dealer);
This works, but what I want to do is only draw a random card if theres no data in the database already. If the user draws, someone could just refresh the page to get a different hand. I want to do something like this:
if ($rs5[hand] == "") {
shuffle($deck);
for ($i = 0; $i < 2; $i++) {
$hand[] = array_shift($deck);
$dealer[] = array_shift($deck);
}
$handstr = serialize($hand);
$deckstr= serialize($deck);
$dealerstr= serialize($dealer);
} else {
$dealer = $rs5[dealer];
$hand = $rs5[hand];
$deck = $rs5[deck];
}
Im getting errors with this, I don't know what I'm doing with arrays really, can anyone point me in the right direction?

I'm not terribly sure what you're trying to do, but for starters:
$dealer = $rs5[dealer];
$hand = $rs5[hand];
$deck = $rs5[deck];
Should probably be:
$dealer = $rs5[$dealer];
$hand = $rs5[$hand];
$deck = $rs5[$deck];
Note the dollar signs on the index variables.

You could do:
if (empty($hand))
or:
if (count($hand) == 0)

Related

I don't know what to do with the probability draw

I am currently giving a score of one or more people and choosing to draw more than one person based on the score. However, there is still a runtime error and is not being resolved. Please let me know how to this problem solve.
this is my code:
$selectChildrens = array();
for($i=0;$i<$recuTotal;$i++){
$random = rand(0,sizeof($childSelectArray)-1);
$selectChild = $childSelectArray[$random];
$sameCheck = 0;
if(sizeof($selectChildrens) == 0){
array_push($selectChildrens,$selectChild);
while(($key = array_search($selectChild,$childSelectArray)) != NULL){
unset($childSelectArray[$key]);
}
$recuTotal—;
$i=0;
}else{
array_push($selectChildrens,$selectChild);
while(($key2 = array_search($selectChild,$childSelectArray)) != NULL){
unset($childSelectArray[$key2]);
}
$recuTotal—;
$i=0;
}
}
I see that your attempt to decrement $recuTotal is not using correct syntax.
Use this line instead: $recuTotal--
You are using a long dash, but need two hyphens.
As for your array_search() lines, I always use: !==false though I'm not sure it matters.
Lastly, you can use !sizeof($selectChildrens) as a shorter if statement.
Though I'll admit I didn't fully comb your code to see what it is doing, this is a DRYer code block that will perform the same way:
$selectChildrens = array();
for($i=0;$i<$recuTotal;$i++){
$random = rand(0,sizeof($childSelectArray)-1);
$selectChild = $childSelectArray[$random];
$sameCheck = 0;
array_push($selectChildrens,$selectChild);
while(($key=array_search($selectChild,$childSelectArray))!==false){
unset($childSelectArray[$key]);
}
$recuTotal--;
$i=0;
}

PHP Number Ticket System?

So, I'm trying to make a ticket system. So a users will be assigned 1000 tickets each, I will then generate a number from 1 to 5000, I then need it to select the user.
The way I have done it was made an array then looped 5000 times and assigned each user a ticket, however this doesn't work with really big numbers like 5,000,000. So I'm trying to think of the best way to do this and I'm unsure how.
Any advice?
$users = array();
$ticketNum = 0;
$result = $MySQL->query("SELECT * FROM `users` ");
while($row = $result->fetch_assoc()){
$i = 0;
while($i < $row['points']){
$i++;
$ticketNum++;
$ar = array("ticketNum" => $ticketNum, "username" => $row['username']);
array_push($users, $ar);
}
}
$winningTicket = 2500;
foreach($players as $ar){
if($winningTicket == $ar['ticketNum']){
//winner
}
}
I'll need more code to suggest a perfect solution, and also know why you want to assign 1000 tickets to a person?
But you could assign a from-to key instead of looping ALL of the numbers through, like
$users[$userNumber]["from"] = 1;
$users[$userNumber]["to"] = 6;
$findNumber = rand(1,6);
$foundUser = false;
foreach($users as $userNumber => $user) {
if ($user["from"] <= $findNumber && $user["to"] >= $findNumber) {
$foundUser = $user;
break;
}
}
if ($foundUser) {
print "Hooray, someone just got a ticket.";
}
but it does sound like a job you would solve in a different manner, maybe through your database.
Edit: I wrote the above before you added your code example, In your case I would probably do the following.
$result = $MySQL->query("SELECT username FROM users ORDER BY RAND() LIMIT 1");
$winningUser = $result->fetch_assoc();
print "We got a winner: ".$winningUser["username"];

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

Pulling specific random values from php array

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;
}

Dynamic text fields values into PHP array

I have a dynamic web form that creates text after the user tells it how many he wants, what I want to do, is to get the info of those text fields into the next form, I've read a question that is
pretty much what I want to do;
But I haven't had any luck so far;
for ($i = 1; $i <= $quantity; $i++) {
echo "<input type='text' class='text' name='classEmpleado[]' id='empleado$i' />";}
When I try to retrieve them I use this;
$empleado[] = $_POST['classEmpleado[]'];
$i = 0;
for ($i = 1; $i <= $quantity; $i++) {
echo "$empleado[$i]<BR><BR>";
}
But I get the error Undefined index: classEmpleado[]
What am I doing wrong?
ANSWERED!
For anyone looking for the same thing, look at the response of Sherbrow,
And you would just have to edit the loop to this
$empleado[] = $_POST['classEmpleado[]'];
$i = 0;
for ($i = 0; $i < $quantity; $i++) {
echo "$empleado[$i]<BR><BR>";
}
If $empleado is not previously declared or just empty, you are looking for that
$empleado = $_POST['classEmpleado']
But if $empleado is an array, and contains data, you may want to merge everything in one only array
$empleado = array_merge($empleado, $_POST['classEmpleado']);
Whichever way you choose, there should be a check to be certain that $_POST['classEmpleado'] is defined and is an array. Something like :
if(isset($_POST['classEmpleado']) && is_array($_POST['classEmpleado'])) {
/* ... */
}
Try $empleado[] = $_POST['classEmpleado'];
When you put name[] at the end of the fieldname, it will be passed to PHP as an array in $_POST with the key of name like so: $_POST['name'] = array(1,2,3,4);
This statement here is wrong ($empleado[] = $_POST['classEmpleado[]'])
If you want to access $_POST the input field named classEmpleado[], you have to do so :
for($i=0; $i<count($_POST['classEmpleado']); $i++)
{
echo $_POST['classEmpleado'][$i] . '<br /><br />';
}

Categories