Author Topic: Questions Array not shuffling  (Read 1501 times)

0 Members and 1 Guest are viewing this topic.

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #30 on: March 17, 2010, 03:18:09 PM »
Ok I will put ever single bit of code I am using down. I really appreciate the help guys.

Index.php
<?php //index.php
session_name("Acronym_Test");
session_start();
$_SESSION['score'] = 0;
$_SESSION['correct'] = array(); 
$_SESSION['wrong'] = array();
$_SESSION['finished'] = 'no'
$_SESSION['num'] = 0;
require_once (
'functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>The Web Acronym Test</title>
<script type="text/javascript" src="start.js"></script>
</head>
<body id="splash">
<div id="wrapper">
<div id="intro">
<h1>Take the test and see how well you know your web acronyms</h1>
<p>Each acronym has 4 possible answers. Choose the answer you think is correct and click <strong>'Submit Answer'</strong>. You'll then be given the next acronym.</p>
<p>There are 20 acronyms, so let's get cracking! You'll get your score at the end of the test. It's just like facebook (honest!).</p>
<div id="leaderboard">
<h2>Top 10 Scorers</h2>
<?php 
 showLeaders
('leaders.xml',10,5);
 
?>
</div><!-- leaderboard-->
</div><!--intro-->
<div id="quiz">
<h2>Start The Test</h2>
<p>If featuring on the Score Board is of absolutely no interest to you,</p>
<form id="jttt" method="post" action="test.php">
<p><input type="submit" value="Just Take The Test" /></p>
</form>
<form id="questionBox" method="post" action="test.php">
<p>If you want to be placed on the 'Top Scorers' list, please enter a username below.</p> 
<ul>
<li><label for="username">Create A Username:</label><br />
<input type="text" id="username" name="username" value="Username" />
<p id="exp">Username must be between 3 and 10 characters in length</p></li>
</ul>
<p><input type="hidden" name="register" value="TRUE" />
<input type="submit" id="submit" value="Register And Take The Test" /></p>
</form> 
<p id="helper"><?php if(isset($_SESSION['error'])) echo $_SESSION['error']; ?></p>
</div><!--quiz-->
</div><!--wrapper-->
</body>
</html>


test.php
<?php //test.php

session_name("Acronym_Test");
session_start();
require_once(
'questionsandanswers.php');
require_once(
'functions.php');
if (!isset(
$_POST['submitter'])) {

    if(isset(
$_POST['register'])) {
	
	
$username trim(strip_tags(stripslashes($_POST['username'])));
	
	
$file "leaders.xml";
 
	
	
$xml simplexml_load_file($file);
	
	
foreach(
$xml->user as $user) {
	
	
	
if (
$user->name == $username) {
 
	
	
	
$_SESSION['error'] = 'That name is already registered, please choose another.';
 
	
	
	
header('Location: index.php');
 
	
	
	
exit();
 
	
	
	
}
 
	
	
}
	

	
	
$_SESSION['user'] = $username;
	
	
$_SESSION['score'] = 0;
	
	
$_SESSION['correct'] = array(); 
	
	
$_SESSION['wrong'] = array();
	
	
$_SESSION['finished'] = 'no';
	
	
if (isset(
$_SESSION['error']))
	
	
unset(
$_SESSION['error']); 
	
	
$num 0;
	
} else {
	
	
$random rand(1,1000);
	
	
$_SESSION['user'] = 'Anon'$random;
	
	
$_SESSION['score'] = 0;
	
	
$_SESSION['correct'] = array(); 
	
	
$_SESSION['wrong'] = array(); 
	
	
$_SESSION['finished'] = 'no';
	
	
$num 0;
	
}
} else {
	
$num = (int) $_POST['num'];
	
$postedanswers str_replace("_"," ",$_POST['answers']);
	
if (
$postedanswers == $answers[$num]['0']) {
	
	
$_SESSION['score']++;
	
	
$_SESSION['correct'][] = $postedanswers
	
} else {
	
	
$_SESSION['wrong'][] = $postedanswers;
	

	
if (
$num count($questions)-1) {
	
	
$num++;
	
} else {
	
	
$last true;
	
	
$_SESSION['finished'] = 'yes';
	
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>The Web Acronym Test</title>
<?php 
if (!isset($last)) {
	
echo 
"<script type=\"text/javascript\" src=\"form.js\"></script>";
}
?>
</head>
<body>
<div id="wrapper">
<div id="intro">
<h1>Take the test and see how well you know your web acronyms</h1>
<p>Each acronym has 4 possible answers. Choose the answer you think is correct and click <strong>'Submit Answer'</strong>. You'll then be given the next acronym.</p>
<p>There are 20 acronyms, so let's get cracking! You'll get your score at the end of the test. It's just like facebook (honest!).</p>
<?php if(isset($_SESSION['user'])) echo "<h4>Current tester: {$_SESSION['user']}</h4>"?>
</div><!--intro-->
<div id="quiz">
<?php 
if (!isset($last)) {  ?>
<h2>Acronym <?php echo $num+1?>:</h2>
<p>What does <strong><?php echo $questions[$num]; ?></strong> stand for?</p>
<form id="questionBox" method="post" action="test.php">
<ul>
<?php 
$pattern 
' ';
$replace '_';
shuffle_assoc($answers[$num]);
foreach (
$answers[$num] as $answer) {
	
$answer2 str_replace($pattern,$replace,$answer);
	
echo 
"<li><input type=\"radio\" id=\"$answer2\" value=\"$answer2\" name=\"answers\" />\n";
	
echo 
"<label for=\"$answer2\">$answer</label></li>\n";
}
?>
</ul>
<p><input type="hidden" name="num" value="<?php echo $num?>" />
<input type="hidden" name="submitter" value="TRUE" />
<input type="submit" id="submit" name="submit" value="Submit Answer" /></p>
</form>
<?php } else { 
$file "leaders.xml";
 
$xml simplexml_load_file($file);
 
$user $xml->addChild('user');
 
$uname $user->addChild('name',$_SESSION['user']);
 
$uscore $user->addChild('score',$_SESSION['score']);
 
$xml->asXML("leaders.xml");
 
echo 
"<h2 id=\"score\">{$_SESSION['user']}, your final score is:</h2>\n
 <h3>
{$_SESSION['score']}/20</h3><h4>Verdict:</h4>";
 if(
$_SESSION['score'] <= 5) echo "<p id=\"verdict\"><span>S</span>everely <span>H</span>indered <span>I</span>n the <span>T</span>est!</p>\n";
 if((
$_SESSION['score'] > 5) && ($_SESSION['score'] <= 10)) echo "<p id=\"verdict\"><span>C</span>ould <span>R</span>ead <span>A</span>nd <span>P</span>ractice more.</p>\n";
 if((
$_SESSION['score'] > 10) && ($_SESSION['score'] <= 15)) echo "<p id=\"verdict\"><span>A</span>cronyms a<span>R</span>e <span>S</span>o <span>E</span>asy!</p>\n";
 if(
$_SESSION['score'] > 15) echo "<p id=\"verdict\"><span>S</span>uper <span>A</span>cronym <span>S</span>pecialist</p>";
 echo 
"<p id=\"compare\"><a href=\"results.php\">See how you compare! <img src=\"images/arrow.png\" /></a></p>";
}
?>
</div><!--quiz-->
</div><!--wrapper-->
</body>
</html>


functions.php
<?php //functions.php

function shuffle_assoc(&$array) {
	
$keys array_rand($arraycount($array));
	
foreach(
$keys as $key)
    
	
$new[$key] = $array[$key];
	
    
$array $new;
        return 
true;
	
}
  
function 
showLeaders($file,$limit,$group null) { 
	
$leaders = array();
	

	
// Load the xml file and place all users and associated 
 
	
// scores into the 'leaders' array.
 
	
$xml simplexml_load_file($file);
 
	
foreach(
$xml->user as $user) {
 
	
	
$name = (string)$user->name;
 
	
	
$score = (string)$user->score;
 
	
	
$leaders[$name] = $score;
 
	
}
 
	
	

 
	
// Sort the leaders array numerically, highest scorers first.
	

 
	
arsort($leaders,SORT_NUMERIC);
 
	

 
	
// Initialise our $counter variable to '1'.
 
	
$counter 1;
 
	

 
	
// Start a html ordered list to hold the leaders.
 
	
$output "<ul class=\"leaders\">\n";
 
	

 
	
// Loop through the 'leaders' array and wrap each username and score
 
	
// in <li> tags. If the user is the current $_SESSION['user'], wrap
 
	
// the name/score in <strong> tags too.
 
	
foreach (
$leaders as $key => $value) {
 
	
	
// Check that $counter is less than $limit.
 
	
	
if (
$counter <= $limit) {
 
	
	
	
if (
$key == $_SESSION['user']) {
 
	
	
	
	
$output .= "<li><strong>$key:</strong> $value/20</li>\n";
 
	
	
	
} else {
 
	
	
	
	
$output .= "<li>$key$value/20</li>\n";
 
	
	
	
}
 
	
	
	
// Check to see if $group parameter has been passed.
 
	
	
	
// If it has, create separate lists according to the $group variable.
 
	
	
	
if (
$group) {
 
	
	
	
	
// Use the modulus operator(%) to create new sub-list.
 
	
	
	
	
if(
$counter $group == 0) {
 
	
	
	
	
	
$output .= "</ul>\n<ul class=\"leaders\">\n";
 
	
	
	
	
}
 
	
	
	
}
 
	
	
}
 
	
// Increment the $counter.
	

 
	
$counter++;
 
	
}
 
	
// End the ordered list.
 
	
$output .= "</ul>\n";
 
	

 
	
// Print out the ordered list.
	
echo 
$output;
 }
 
function 
showAnswers($answers,$questions) { 
	
for(
$x 0$xcount($answers); $x++) {
	
	
if (
$x == 0) { 
	
	
 
	
$output "<div class=\"qanda clear\">\n";
	
	
} else { 
	
	
	
$output "<div class=\"qanda\">";
  
	
	
}
 
	
$output .= '<h4>Anacronym' . ($x+1) . ': ' $questions[$x] . '</h4>'
	
$output .= "<ol>\n";
 
	
for (
$y 0;$ycount($answers[$x]); $y++) {
 
	
	
if ((
$answers[$x][$y] === $answers[$x][0]) && (in_array($answers[$x][$y],$_SESSION['correct']))) {
 
	
	
	
$output .= "<li class=\"correctuser\">{$answers[$x][$y]} (Correct!)</li>\n";
 
	
	
} else if (
$answers[$x][$y] === $answers[$x][0]) {
 
	
	
	
$output .= "<li class=\"correct\">{$answers[$x][$y]}</li>\n";
 
	
	
} else if (
in_array($answers[$x][$y],$_SESSION['wrong'])) {
 
	
	
	
$output .= "<li class=\"wrong\">{$answers[$x][$y]} (Woops!)</li>\n";
 
	
	
} else { 
 
	
	
	
$output .= "<li>{$answers[$x][$y]}</li>\n";
	
	
}
	
}
	
$output .= "</ol></div>\n";
	
echo 
$output;
	
}
}
?>
	



questionsandanswers.php
<?php
$questions 
= array('FTP','AJAX','RSS','XSS','PHP','W3C','XML','YUI','HTML','CGI','SSL','SQL','HTTP','CSS','SOAP','WAI','SSI','JSON','XSLT','WCAG');
$answers = array(
array(
=>'File Transfer Protocol','Force Through Privately','File Through Protocol','File Test Protocol'),
array(
=> 'Asynchronous JavaScript and XML','All JavaScript and XML','Alternative Java and XML','Actual JavaScript and XML'),
array(
=> 'Really Simple Syndication','Really Simple Scripting','Ready-Styled Scripting','Really Stupid Syndication'),
array(
=> 'Cross-site Scripting','Cross-site Security','Cleverly Structured Scripting','eXtremely Safe and Secure'),
array(
=> 'PHP: Hypertext Preprocessor','Post Hypertext Processor','Practical HTML Processing','Process HTML Prettily'),
array(
=> 'World Wide Web Consortium','World Wide Web Committee','World Wide Web Creatives','Wakefield Willy Wavers Club'),
array(
=> 'eXtensible Markup Language','eXtendable Markup Language','Crossover Markup Language','eXtreme Markup Language'),
array(
=> 'Yahoo User Interface','Yahoo\'s Useful Idea','Yahoo Utility Interface','Yahoo User Interaction'),
array(
=> 'Hypertext Markup Language','Human Markup Language','Helpful Markup Language','Hypertext Memory Language'),
array(
=> 'Common Gateway Interface','Common or Garden Interaction','Computer\'s Graphical Intelligence','Common Graphical Interface'),
array(
=> 'Secure Sockets Layer','Server Security Layer','Server Security Level','Secret Socket Layer'),
array(
=> 'Structured Query Language','Stupid Query Language','Secure Query Language','Strict Query Language'),
array(
=> 'Hypertext Transfer Protocol','Hypertext Traffic Protocol','HTML Traffic Transfer Protocol','HTML Through Traffic Protocol'),
array(
=> 'Cascading Style Sheets','Custom Style Sheets','Clientside Style Sheets','Calculated Style Sheets'),
array(
=> 'Simple Object Access Protocol','Structured Object Access Protocol','Simple, Objective And Private','Simply Obvious Access Principle'),
array(
=> 'Web Accessibility Initiative','World Wide Accessibility Intiative','World Wide Accessibility Incorporation','Web Accessibility and Inclusion'),
array(
=> 'Server-Side Include','Server-Side Intelligence','Scripted Server Include','Secure Server Include'),
array(
=> 'JavaScript Object Notation','JQuery-Scripting Object Notation','Just Simple Object Notation','JavaScript Over the Net'),
array(
=> 'eXtensible Stylesheet Language Transformation','eXpandable Stylesheet Language Transfer','eXtensible Stylesheet Language Transfer','eXtendable Stylesheet Language Transformation'),
array(
=> 'Web Content Accessibility Guidelines','Wakefield Community Action Group','Web Criteria And Guidelines','World-wide Common Access Group')
); 
?>


results.php
<?php //results.php
session_name("Acronym_Test");
session_start();
if(
$_SESSION['finished'] != 'yes') {
header('Location: index.php');
}
include_once(
'questionsandanswers.php');
include_once(
'functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>The Web Acronym Test Results</title>
</head>
<body id="resultpage">
<div id="wrapresult">
<h1>The Results Page For <span><?php echo $_SESSION['user']; ?></span></h1>
<div id="intro">
<h2>Top 20 Scorers</h2>
<?php showLeaders('leaders.xml',20); ?>
</div><!--intro-->
<div id="quiz">
<?php showAnswers($answers,$questions); ?>
	

</div><!--quiz-->
<ul id="footer" class="clear">
<li><a href="index.php" title="Start The Quiz Again">Start Again</a></li>
<li><a href="http://www.elanman.co.uk/2009/03/make-your-own-php-quiz-part-1/" title="Return To ElanMan's Drawers">Return To The Blog</a></li>
</ul>
</div><!--wrapper-->
</body>
</html>


leaders.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
  <user>
  
	
<name>Bobby</name>
    <score>10</score>
  </user>
  <user>
  
	
<name>Billy</name>
    <score>1</score>
  </user>
</users>


start.js
window.onload = function () {
	
document.getElementById('username').onfocus = function(evt) {
	
	
if(
this.value == 'Username'this.value '';
	
	
document.getElementById('helper').innerHTML '';
	
	
}
	
document.getElementById('username').onblur = function(evt) {
	
	
if(
this.value == ''this.value 'Username';
	
	
}
	
document.getElementById('questionBox').onsubmit = function() {return checkForm();};
}

function 
checkForm() {
	
if ((
document.getElementById('username').value == '') || (document.getElementById('username').value == 'Username') || (document.getElementById('username').value.length 3) || (document.getElementById('username').value.length 10)) {
	
document.getElementById('helper').innerHTML 'To register, please enter your own username between 3 and 10 characters in length';
	
	
return 
false;
	
}
}


form.js
window.onload = function () {
	
document.getElementById('submit').disabled true;
	
var 
qform document.getElementById('questionBox');
	
var 
inputs qform.getElementsByTagName('input');
	
for(var 
0inputs.length;i++) {
	
	
inputs[i].onclick = function(evt) { checkForm();};
	
}
}

function 
checkForm() {
	
document.getElementById('submit').disabled false;
}


Thats EVERYTHING every single bit of code involved in this. Thanks for the help. Any help you can give would be amazing!

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #31 on: March 17, 2010, 05:25:03 PM »
There was a CSS file as well but that shouldn't matter right?

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #32 on: March 18, 2010, 08:26:52 AM »
Was any of this helpful? Any idea from my mass of code what is causing the problem?

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #33 on: March 18, 2010, 10:30:10 AM »
I just noticed you can attach files. Here is all the source files downloaded all ready to go. I havn't touched them at all. They just dont shuffle for me.
Sorry I didn't post this before. I just noticed now that you can include files.

[attachment deleted by admin]

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,754
    • View Profile
Re: Questions Array not shuffling
« Reply #34 on: March 18, 2010, 11:24:35 AM »
There is obviously something wrong in your code. Attach the files you are using and we can take a look at the full code.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #35 on: March 18, 2010, 11:25:58 AM »
I did attach it. Look at the post directly above that one you posted. There is a zip file that contains everything.

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,754
    • View Profile
Re: Questions Array not shuffling
« Reply #36 on: March 18, 2010, 11:40:09 AM »
Yes, I DID see that. I was responding to your statements "I just noticed you can attach files ... I just noticed now that you can include files." Funny how you just noticed that today when I mentioned it yesterday.

I already copied the code from your post yesterday. I just haven't had the time to sift through it.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #37 on: March 18, 2010, 11:44:20 AM »
I know I am a dofus. I thought by attach you meant just put it down. I dont know why. My head is away these past couple of days. I was posting earlier and noticed the attach thing. Sorry. But I really appreciate the help thanks.

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #38 on: March 22, 2010, 09:42:00 AM »
Have you had any luck mjdamato? or had a chance to look over the code at all yet?

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,754
    • View Profile
Re: Questions Array not shuffling
« Reply #39 on: March 22, 2010, 11:41:43 AM »
Have you had any luck mjdamato? or had a chance to look over the code at all yet?

Upon initial inspection it did seem to present the same problem, but then after playing around with it for a while it seemed to work correctly. I have to assume that it has something to do with the SESSION variables. I haven't had time to dive into it more. Personally, it wouldn't be worth my time. I could probably rewrite a better solution in less time than it would take to fix that code. But, I just don't have the time right now.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #40 on: March 22, 2010, 11:45:15 AM »
You cant post the code you messed about with to get it working or anything? or what you changed to get it working correctly?
?

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,754
    • View Profile
Re: Questions Array not shuffling
« Reply #41 on: March 22, 2010, 12:27:54 PM »
You cant post the code you messed about with to get it working or anything? or what you changed to get it working correctly?
?

Well, I was only modifying the code to output data to the screen so I could see some of the internal variables to see what was going on. When it started to work I undid my changes, and it continued to work. So, the problem was not "fixed" by anything I did. That is why I assume it has something to do with the session variables.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #42 on: March 22, 2010, 12:33:32 PM »
Alrighty. Well thanks for all the help much appreciated.

Offline lynxjava

  • Irregular
  • Posts: 1
    • View Profile
Re: Questions Array not shuffling
« Reply #43 on: April 27, 2010, 05:18:32 PM »
Hey guys,

I dont know what the big deal is.
The answer is really simple and you guys just missed out a line.
Just copy and paste this code and it would work fine.

I have highlighted in bold the missing line which should of been included.

function shuffle_assoc(&$array) {
   $keys = array_rand($array, count($array));
   shuffle($keys);
   foreach($keys as $key)
       $new[$key] = $array[$key];
       $array = $new;
        return true;
   }


I found the answer by looking up some coding on the php.net

Hope this solved your problems :)