Search the Community
Showing results for tags 'arrays'.
-
Hi, Phreaks, I've made a number in inquiries into roughly the same problem. For that I apologize but I'm really confused and frustrated and can't work this seemingly simple problem out. Like before, I'm trying to make an associative array out of DB data and I can't work out some of the results I'm getting. If I use this code here -> <?php public function all($column = "") { $items = array(); foreach($this->_results as $item) { echo $item->id . " => " . $item->category . " "; } } I get this -> Excellent, so far But if I do this -> <?php public function all($column = "") { $items = array(); foreach($this->_results as $item) { $items [] = [$item->id => $item->category]; print_r($items); } } I get back a whole mound of data -> Why? I don't get it. Why is building this assoc array with category_id as the key and category as the value so difficult. I don't understand why this second code isn't making that arrray
-
I'm making a registration form and I'm really new at it. I've had a look about at similar issues but feel like I've got my code set up right, I obviously don't. I have a registration_handler.php and a functions.php file. I'm simply trying to pass an array ($errors[]) from the functions that generate them to a function that prints them out on registration_handler.php. It seems so easy, but I'm not getting it. Here's my code: from functions.php: (this is just an example of one of the functions) // USERNAME (MANDATORY) //uses the clean_names() and checks for empty input function assign_username() { global $conn; $username = $_POST['username']; if(!$username){ $errors[] = "A username is mandatory"; echo "A username is mandatory <br>"; } else { $username = clean_names($username); } //check for duplicate username and return $username if doesn't exist already $username_check = mysqli_query($conn, "SELECT username FROM users WHERE username='$username'"); $number_rows = mysqli_num_rows($username_check); if($number_rows > 0) { $errors[] = "Username already in use <br>"; echo "Username already in use <br>"; } else { return $username; } return $errors; } // END USERNAME Also from functions.php, the function to print out the error array: //display error array function show_errors($errors) { print_r($errors); } and the function call from registration_handler.php: if(isset($_POST['register_button'])) { //assign clean form variables $firstname = assign_firstname(); $lastname = assign_lastname(); $username = assign_username(); $email = assign_email(); $password = assign_password(); $date = date("Y-m-d"); $errors = array(); show_errors($errors); } I'm intentionally leaving the username out to test this on the form but I only get returned Array() It echos "Username is mandatory" but it seems like it's not passing the error string to the error array Can anyone point me towards what I'm doing wrong, please. I appreciate the replies
-
I am trying to get rows from MYSQL table (attachment) based on: Select last five rows where status_id = 1 Select last two rows where status_id = 2 *I did use UNION with two SELECT queries to get whole data as one array. Now on PHP side... I have first block for rows having status_id 1 so if there are rows having status_id 1 then PHP should display the data otherwise if there is no row having status_id 1 then PHP should print NO DATA only once. I have second block for rows having status_id 2 so if there are rows having status_id 2 then PHP should display the data otherwise if there is no row having status_id 2 then PHP should print NO DATA only once. I did use foreach loop then within loop i did use if condition to check status_id of rows. it works fine when i omit NO DATA part but when i add it. the result shows both rows and NO DATA in first block when there are one or more rows having status_id 1 but no row having status_id 2 Which made me believe that i was doing it the wrong way. Please guide me *PS: I know its PHP section the thread should be related to PHP problem but... is it right to use UNION in query? or should i post a new thread in relevant section for guidance?
-
Hi all, Need help in solving this task using PHP built in function : array_reverse() and without it. Appreciate it in explaining the code as I'm completely a newbie. function reverseArray($Arr) { } $fruits = ["Mango","Strawberry","Bananas","Pineapple"]; $result = reverseArray($fruits); Many thanks,
-
I dont understand arrays in PHP and its necessary to finally fess up and ask for help. It seems so trivial,, but I've spent Whole DAYS trying to make sense of this. (I came from assemble language programming). I am receiving UDP packets of a known size. in this case, 4 bytes of binary data. It gets unpacked ( I dont know why. I cut and pasted this simple parser from an example). All I want is the array[0] byte. I'm trying to avoid complex loops and pointers. // First lets grab a data packet and put our few bytes into the variable $buf while(1) { socket_recvfrom($socket, $buf, 16, 0, $from, $port); // Easy! but the UDP data in $buf is binary not useful like this. //Convert to array of decimal values $array = unpack("C*", $buf); // 'C' tells unpack to make unsigned chars from the binary. //Convert decimal values to ASCII characters: $chr_array = array(); // wait a second. What is happening here? for ($i = 0; $i < count($array); $i++) { $chr_array[] = chr($array[$i]); // Whats going on here? Anyone? } // So now I can assume the first byte of this $chr_array[] is my prize, right? $mychr = chr_array[0]; // Nope. Looking at $chr_array[0] either reveals a zero or the actual word "Array", depending on how late I've stayed up. print_r($array); // This is my debugger. It shows SOMETHING is working. echo "Received $mychr from remote $address $from and remote port $port" . PHP_EOL; } socket_close($sock); Output of above code... assuming the value read was 60 decimal: Array ( [1] => 60 [2] => 0 [3] => 0 [4] => 0 ) Received 0 from remote address nnn.nnn.nnn.nnn and remote port 8888 So print_r knows what to do, the last line of my code doesn't. Any help would be appreciated, as this goes to the heart of my issue of being mystified by how PHP makes and processes arrays. Its clearly not just a string of numbers. I'm trying to pull ONE printable number from that buffer. Halp!
-
Hi all, I am trying to echo reset($starttimes) to show the first value in my $starttimes array however i it is only showing the second value in the array and skipping the first i want to echo. The statement I have written is inside a while statement however I am not sure if that is where lies the problem. Please take a look at line 29 here: http://pastebin.com/2KQ7kgy9
-
I have to complete a multidimensional array, I have written PHP code but I keep getting numbers ontop of the arrays? Moreover; could you give me feedback on the multidimensional array is it anygood? <?php $customers = array( $customers =['Name' => 'Bob','id' => '587','Date' => '17/10/1015',], $customers =['Name' => 'Stu','id' => '100','Date' => '02/04/2010', ], $customers =['Name' => 'Kate','id' => '12','Date' => '09/12/2013',], ); $keys = array_keys($customers); $keys = array_keys($customers); for($i = 0; $i < count($customers); $i++) { echo $keys[$i] . "<br>"; foreach($customers[$keys[$i]] as $key => $value) { echo $key . " : " . $value . "<br>";} echo "<br>";} ?> //Ouput: 0Name : Bobid : 587Date : 17/10/1015 1Name : Stuid : 100Date : 02/04/2010 2Name : Kateid : 12Date : 09/12/2013
-
I have to complete a simple task which says 'use foreach to print the value of the sum of two cards, the deck has 16 cards and each card has one number and one colour'. Moreover; I can write four cards and four numbers, but how do I write all sixteen cards (I would prefer if they could sit abreast - parallel to each other)? The code I have so far is this: <?php $a = array( "Red" => 1, "Blue" => 2, "Green" => 3, "Yellow" => 4, ); foreach ($a as $key => $val) { echo "<h4>$key => $val.</h4>"; } ?> // Output: Red => 1. Blue => 2. Green => 3. Yellow => 4.
-
I'm developing a database-powered quiz and need help upgrading the basic script. The original script (posted below) works fine, but it has some limitations. So someone suggested an alternate script (posted next) that turns each answer (or group of answers into an array within an array. However, I can't get the new script to work. My latest attempt is posted below the first two scripts. var_dump($_POST) tells me that the answer key ($answers) is working in all examples, but that's about all. One error message I'm getting is array_diff(): Argument #1 is not an array - in reference to this code: if(is_array($answer)){ if(array_diff($qa[$num], $answer) == array()){ I get the same error message if I change it to this: if(array_diff($qa, $answer) == array()){ If a quiz has 10 questions, then each question has an ID (e.g. q1 or q10). If the first question has four possible answers, each answer has its own ID, from q1-A to q1-D. I posted the HTML for two questions at the end of this post. Sorry for all the code. I think my problem is relatively simple, but I just can't figure out what I'm doing wrong. Thanks! ORIGINAL SCRIPT if (isset($_POST)): $totalCorrect = 0; $answers = array(1 => 'A', 2 => 'Jupiter', 3 => 'C', 4 => 'D', 5 => 'A', 6 => 'C', 7 => 'C', 8 => 'C', 9 => 'B', 10 => array('A','B','C')); foreach ($answers as $num => $answer): $question = 'q'.$num; if(is_array($answer) && isset($_POST[$question])){ $ans_cnt = count($answer); $ans_value = (1 / $ans_cnt); $post_cnt = count($_POST[$question]); //find matches between answer array and post array $matches = array_intersect($answer,$_POST[$question]); $good_answers = count($matches); //Get bad answer count, which be be subtracted from overall score $bad_answers = 0; foreach($_POST[$question] as $post_answer): if(!in_array($post_answer,$answer)): $bad_answers++; endif; endforeach; if($good_answers ==3 && $bad_answers==0){ $result = 1; }else{ $result = 0; } if(($post_cnt != $ans_cnt) || ($post_cnt == $ans_cnt && $ans_cnt != count($matches))){ $result = $result * $ans_value; $totalCorrect = $totalCorrect + $result; }else{ $totalCorrect++; } }elseif(isset($_POST[$question]) && strtolower($_POST[$question]) === strtolower($answer)){ $totalCorrect++; } endforeach; $pct = round( (($totalCorrect/count($answers)) * 100), 0); echo $totalCorrect.' correct ('.$pct.'%)'; endif; REVISED SCRIPT if ($_SERVER['REQUEST_METHOD'] == 'POST') { $qa = 'q'.$num; $correct = 0; $answers = array(1 => array('A'), 2 => array('Jupiter'), 3 => array('C'), 4 => array('D'), 5 => array('A'), 6 => array('C'), 7 => 'C', 8 => 'C', 9 => 'B', 10 => array('A','B','C')); $total = count($answers); foreach($answers as $k => $v){ if(is_array($v)){ if(array_diff($qa[$k], $v) == array()){ $correct++; } } else if($qa[$k] === $v){ $correct++; } } $grade= ($correct/count($answers))*100; echo"<p>Score $grade%</p>"; } MY LATEST TEST if ($_SERVER['REQUEST_METHOD'] == 'POST') { $correct = 0; $answers = array(1 => array('A'), 2 => array('Jupiter'), 3 => array('C'), 4 => array('D'), 5 => array('A'), 6 => array('C'), 7 => 'C', 8 => 'C', 9 => 'B', 10 => array('A','B','C')); $total = count($answers); foreach($answers as $num => $answer){ $qa = 'q'.$num; if(is_array($answer)){ if(array_diff($qa[$num], $answer) == array()){ $correct++; } } else if($qa[$num] === $answer){ $correct++; } } $grade= ($correct/count($answers))*100; $grade2= ($correct/count($answer))*100; echo"<p>Score $grade%</p>"; echo"<p>Score2 $grade2%</p>"; // echo $totalCorrect.' correct ('.$grade.'%)'; } SOME HTML <li id="q9"> <div class="Question">Scientists believe the universe is:</div> <div class="Answer"> <label class="Wide" for="q9-A"><div class="Radio"><input type="radio" name="q9" id="q9-A" value="A" style="display: none;"> A. disappearing</div></label></div> <div class="Answer"> <label class="Wide" for="q9-B"><div class="Radio"><input type="radio" name="q9" id="q9-B" value="B" style="display: none;"> B. expanding</div></label></div> <div class="Answer"> <label class="Wide" for="q9-C"><div class="Radio"><input type="radio" name="q9" id="q9-C" value="C" style="display: none;"> C. contracting</div></label></div> <div class="Answer"> <label class="Wide" for="q9-D"><div class="Radio"><input type="radio" name="q9" id="q9-D" value="D" style="display: none;"> D. becoming bipolar</div></label></div> </li> <li id="q10"> <div class="Question">Check each item that can be found in our solar system.</div> <div class="Answer" style="margin-top: 5px; background: #000; color: #fff; text-align: center;"> <label for="q10-A"><input type="checkbox" name="q10[]" id="q10-A" value="A">planet</label> <label for="q10-B"><input type="checkbox" name="q10[]" id="q10-B" value="B">asteroid</label> <label for="q10-C"><input type="checkbox" name="q10[]" id="q10-C" value="C">comet</label> <label for="q10-D"><input type="checkbox" name="q10[]" id="q10-D" value="D">black hole</label> <label for="q10-E"><input type="checkbox" name="q10[]" id="q10-E" value="E">neutrino star</label> <label for="q10-F"><input type="checkbox" name="q10[]" id="q10-F" value="F">quasar</label> </div> </li>
-
Need Help!!! I am trying to build an application in php without database connectivity. I have a index page where i have 6 users. 1 among the 6 users will act as admin. I am using array to get the username & password When the users logs in, some of the options should be disabled or non-editable. Assume "raj" plays the admin role Code what i have: <?php session_start(); /* Starts the session */ /* Check Login form submitted */ if(isset($_POST['Submit'])){ /* Define username and associated password array */ $logins = array('raj' => 'raj123@123','ram' => 'ram@123','dev' => 'dev@123','dave' => 'dave@123','Sugi' => 'sugi@123','raki' => 'raki@123','sam' => 'sam@123'); /* Check and assign submitted Username and Password to new variable */ $Username = isset($_POST['Username']) ? $_POST['Username'] : ''; $Password = isset($_POST['Password']) ? $_POST['Password'] : ''; /* Check Username and Password existence in defined array */ if (isset($logins[$Username]) && $logins[$Username] == $Password){ /* Success: Set session variables and redirect to Protected page */ $_SESSION['UserData']['Username']=$logins[$Username]; header("location:signin.php"); exit; } else { /*Unsuccessful attempt: Set error message */ $msg="<span style='color:red'>Invalid Login Details</span>"; } } ?> Any help on this will be much appreciated!!!! Thanks
- 1 reply
-
- php
- no database
-
(and 1 more)
Tagged with:
-
Hi, I am working on a betting API, The data comes from an XML Feed. I am using a PHPPhar file to iterate the XML data, Seems to work really well. What I need to do now is iterate each "outcome" type and order it by the highest decimal to lowest decimal value (Best odds) My current array of data from the XML looks like this (See pastebin for full version) : SimpleXMLElement Object ( [Outcome] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 1 [name] => 1X2 ) [Bookmaker] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 8 [name] => Bet365 [isLive] => false [lastUpdate] => 2015-01-15T04:17:03 [bookieEventID] => [bookieLeagueID] => [BookieOfferTypeID] => 40 ) [Odds] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 10026743121640944 [bet] => 1 [startPrice] => 9/2 [currentPrice] => 5/1 [line] => [LastUpdate] => 2015-01-15T04:17:03 [bookieOutcomeID] => [Status] => Open ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 10026743131640944 [bet] => 2 [startPrice] => 31/50 [currentPrice] => 57/100 [line] => [LastUpdate] => 2015-01-15T04:17:03 [bookieOutcomeID] => [Status] => Open ) ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 10026743511640944 [bet] => X [startPrice] => 11/4 [currentPrice] => 3/1 [line] => [LastUpdate] => 2015-01-14T17:55:48 [bookieOutcomeID] => [Status] => Open ) ) ) )[1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 2 [name] => Under/Over ) [Bookmaker] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 8 [name] => Bet365 [isLive] => false [lastUpdate] => 2015-01-15T15:25:31 [bookieEventID] => [bookieLeagueID] => [BookieOfferTypeID] => 981 ) [Odds] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 14185280871640944 [bet] => Over [startPrice] => 1/20 [currentPrice] => 3/50 [line] => 0.5 [LastUpdate] => 2015-01-15T15:15:14 [bookieOutcomeID] => [Status] => Open ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 8219239561640944 [bet] => Over [startPrice] => 9/50 [currentPrice] => 1/5 [line] => 1.25 [LastUpdate] => 2015-01-15T08:30:43 [bookieOutcomeID] => [Status] => Open ) ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 13305582441640944 [bet] => Over [startPrice] => 29/100 [currentPrice] => 8/25 [line] => 1.5 [LastUpdate] => 2015-01-15T15:25:31 [bookieOutcomeID] => [Status] => Open ) ) [3] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 15814388431640944 [bet] => Over [startPrice] => 7/20 [currentPrice] => 2/5 [line] => 1.75 [LastUpdate] => 2015-01-15T08:30:43 [bookieOutcomeID] => [Status] => Open ) ) [4] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 9542253841640944 [bet] => Over [startPrice] => 9/20 [currentPrice] => 13/25 [line] => 2.0 [LastUpdate] => 2015-01-15T08:53:07 [bookieOutcomeID] => [Status] => Open ) ) [5] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 18435608691640944 [bet] => Over [startPrice] => 17/25 [currentPrice] => 77/100 [line] => 2.25 [LastUpdate] => 2015-01-15T08:53:07 [bookieOutcomeID] => [Status] => Open ) )[2] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 17 [name] => Both Teams To Score ) [Bookmaker] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 8 [name] => Bet365 [isLive] => false [lastUpdate] => 2015-01-14T17:55:48 [bookieEventID] => [bookieLeagueID] => [BookieOfferTypeID] => 10150 ) [Odds] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 14294083431640944 [bet] => No [startPrice] => 83/100 [currentPrice] => 73/100 [line] => [LastUpdate] => 2015-01-14T17:55:48 [bookieOutcomeID] => [Status] => Open ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 18070790851640944 [bet] => Yes [startPrice] => 83/100 [currentPrice] => 1/1 [line] => [LastUpdate] => 2015-01-14T17:55:48 [bookieOutcomeID] => [Status] => Open ) ) ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 31 [name] => William Hill [isLive] => false [lastUpdate] => 2015-01-15T15:58:30 [bookieEventID] => [bookieLeagueID] => [BookieOfferTypeID] => 226344747 ) [Odds] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 11341591031640944 [bet] => No [startPrice] => 73/100 [currentPrice] => 67/100 [line] => [LastUpdate] => 2015-01-15T15:58:30 [bookieOutcomeID] => [Status] => Open ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 10996680931640944 [bet] => Yes [startPrice] => 1/1 [currentPrice] => 11/10 [line] => [LastUpdate] => 2015-01-15T15:58:30 [bookieOutcomeID] => [Status] => Open ) ) ) ) Is it possible build an array of outcomes, Then sort by the best decimal price. (I have a function built that can convert the "currentPrice" to decimal. Thnak You!
-
Hi all, I am using foreach statement to gather records and program levenshtein to detect any misspellings and suggesting the correct words. The thing is i am unable to convert all those strings into a single array. After trying to correct this issue so many times, i wonder if it is really possible to convert strings into a single array? Any input is welcome
-
I have an array that has several amounts (based on $$$ sales) attached to a 'name' 'id' and 'goal'. As you can see some of the names, id's, and goals are the same. My goal is to gather a total of amounts and attach each total to whichever 'name', 'id', and 'goal' that made the sale. I'm honestly not sure how to go about this as I'm still learning. Array ( [0] => Array ( [name] => L.Chane [id] => oper-4bceffd1-21e0af5b [goal] => 2014-10-25000 [amount] => 360.00 ) [1] => Array ( [name] => L.Chane [id] => oper-4bceffd1-21e0af5b [goal] => 2014-10-25000 [amount] => 450.00 ) [2] => Array ( [name] => L.Chane [id] => oper-4bceffd1-21e0af5b [goal] => 2014-10-25000 [amount] => 450.00 ) [3] => Array ( [name] => C.James [id] => oper-4c236420-0b11e945 [goal] => 2014-10-25000 [amount] => 370.00 ) [19] => Array ( [name] => C.James [id] => oper-4c236420-0b11e945 [goal] => 2014-10-25000 [amount] => 175.00 ) [20] => Array ( [name] => C.James [id] => oper-4c236420-0b11e945 [goal] => 2014-10-25000 [amount] => 155.00 )[61] => Array ( [name] => K.Crass [id] => oper-4c597644-402490ee [goal] => 2014-10-25000 [amount] => 200.00 ) [62] => Array ( [name] => K.Crass [id] => oper-4c597644-402490ee [goal] => 2014-10-25000 [amount] => 599.00 ) [63] => Array ( [name] => K.Crass [id] => oper-4c597644-402490ee [goal] => 2014-10-25000 [amount] => 50.00 ) [113] => Array ( [name] => R.Cervantes [id] => oper-4f05a90b-03b379f9 [goal] => 2014-10-25000 [amount] => 450.00 ) [114] => Array ( [name] => R.Cervantes [id] => oper-4f05a90b-03b379f9 [goal] => 2014-10-25000 [amount] => 589.00 ) [115] => Array ( [name] => R.Cervantes [id] => oper-4f05a90b-03b379f9 [goal] => 2014-10-25000 [amount] => 350.00 ) [166] => Array ( [name] => A.Gerred [id] => oper-4f30019a-27f27473 [goal] => 2014-10-25000 [amount] => 375.00 ) [167] => Array ( [name] => A.Gerred [id] => oper-4f30019a-27f27473 [goal] => 2014-10-25000 [amount] => 294.50 ) [168] => Array ( [name] => A.Gerred [id] => oper-4f30019a-27f27473 [goal] => 2014-10-25000 [amount] => 440.00 ) [202] => Array ( [name] => G.Whitcher [id] => oper-4f300d33-de9592e3 [goal] => 2014-10-25000 [amount] => 5.00 ) [203] => Array ( [name] => G.Whitcher [id] => oper-4f300d33-de9592e3 [goal] => 2014-10-25000 [amount] => 310.00 ) [204] => Array ( [name] => G.Whitcher [id] => oper-4f300d33-de9592e3 [goal] => 2014-10-25000 [amount] => 349.00 ) [235] => Array ( [name] => K.Lawrence [id] => oper-50f6e4ad-9effbec7 [goal] => 2014-10-25000 [amount] => 499.00 ) [236] => Array ( [name] => K.Lawrence [id] => oper-50f6e4ad-9effbec7 [goal] => 2014-10-25000 [amount] => 187.50 ) [237] => Array ( [name] => K.Lawrence [id] => oper-50f6e4ad-9effbec7 [goal] => 2014-10-25000 [amount] => 170.00 ) [246] => Array ( [name] => K.Chane [id] => oper-52657816-3d6516e2 [goal] => 2014-10-25000 [amount] => 375.00 ) [247] => Array ( [name] => K.Chane [id] => oper-52657816-3d6516e2 [goal] => 2014-10-25000 [amount] => 187.50 ) [248] => Array ( [name] => K.Chane [id] => oper-52657816-3d6516e2 [goal] => 2014-10-25000 [amount] => 229.50 ) [256] => Array ( [name] => J.Stewart [id] => oper-qtgjvw8y-1uqtw058 [goal] => 2014-10-25000 [amount] => 170.00 ) [257] => Array ( [name] => J.Stewart [id] => oper-qtgjvw8y-1uqtw058 [goal] => 2014-10-25000 [amount] => 584.00 ) [258] => Array ( [name] => J.Stewart [id] => oper-qtgjvw8y-1uqtw058 [goal] => 2014-10-25000 [amount] => 249.50 ) ) Here is my code so far (And I know it's not clean, because I'm not using PDO yet, I'm just trying to get it to work): $result = mysql_query("SELECT a.*,u.OperatorName,u.MonthlyGoal FROM tblUserPayments a LEFT JOIN tblOperatorGoals u ON a.OperatorID = u.OperatorID WHERE a.ChargeAmount IS NOT NULL AND a.PaymentStatus='OK' AND a.PaymentDate LIKE '$currentDate%' AND u.MonthlyGoal LIKE '$currentDate%' " ); while ($row = mysql_fetch_assoc($result)) { $operArray[] = array( 'name' => $row['OperatorName'], 'id' => $row['OperatorID'], 'goal' => $row['MonthlyGoal'], 'amount' => $row['ChargeAmount']); } foreach ($operArray as $value) { if($value['id'] == '' || $value['id'] == null) { continue; } if(array_key_exists($value['id'], $operSums)) { $operSums[$value['id']] += $value['amount']; } else { $operSums[$value['id']] = $value['amount']; } } Any help is greatly appreciated. Associative arrays are just not my cup of tea.
-
I have a HTML form with a drop down list, which has my entire buyers list populated from the database. In addition to that, I have an option on the top of the drop down such as : <select name="sms_buyer"> <option value="alll">ALL</option> <?php require_once '../model/notifications.php'; @$result2= Notifications::getAllBuyers(); while($value2=mysql_fetch_assoc($result2)){ ?> <option value="<?php echo $value2['buyer_code']; ?>"> <?php echo $value2['buyer_name'] ?> </option> <?php } ?> </select> In the Controller I have the following code segment: function sendNotificationSMS(){ $sms_buyer=$_REQUEST['sms_buyer']; $sms_message=$_REQUEST['sms_message']; $sender='MY CLIENT'; $url='http://localhost:9333/ozeki?'; $url.="action=sendMessage"; $url.="&login=admin"; $url.="&password=abc123"; $obj=new Notifications(); if($sms_buyer=='alll'){ require_once '../model/notifications.php'; $obj=new Notifications(); $result=$obj->getAllBuyers(); while($value=mysql_fetch_assoc($result)){ $rec[]=$value['tel_no']; } foreach ($rec as $recepient) { $url.="&recepient=".urlencode($recepient); } } else{ $res=$obj->getBuyerTelNo($sms_buyer); $sms=mysql_fetch_assoc($res); $recepient=$sms['tel_no']; $url.="&recepient=".urlencode($recepient); } $message=$sms_message; $message.=' Thank You.'; $url.="&messageData=".urlencode($message); $url.="&sender=".urlencode($sender); file($url); header("location:../view/send_notifications.php?s=3#sent"); } If I type print_r($url), the output which I am intending is not appearing... Sending SMS to a single recepient is fine. The problem is sending sms to multiple recepients. Any help is appreciated. Thanks.
-
I want to create a singleton class that read multidimensional array from txt file and flatten the array retrieved. This is what I have tried so far: class singleton { protected static $instance = null; public static function getInstance() { if (!isset(static::$instance)) { static::$instance = new static; } return static::$instance; } public static function flattenArray($array) { $return = array(); $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); foreach ($iterator as $value) { $return[] = $value; } return $return; } public static function loadFile($path) { $file_handle = fopen($path, "r"); while (!feof($file_handle)) { $line = fgets($file_handle); $rawarray[] = $line; } $flattedarray = self::flattenArray($rawarray); fclose($file_handle); return $flattedarray; } With the txt file containing: array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g') I run the class with: include 'singleton.php'; $singleton = singleton::getInstance(); $flattedarray = $singleton->loadFile("file.txt"); echo '<pre>'; print_r($flattedarray); echo'</pre>'; I get as a result: Array ( [0] => array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g') ) Which is the same array found in the txt file. how can i do it without using eval. What am I doing wrong ?
-
I have users in my database with many stored points ie age, gender, interests etc. about 20 points in all. I have a table of products that I want to recommend only applicable products. They each have saved like minage, maxage, gender, interest etc for the ideal consumer. ie dress gender=f This is the bare bones of what I have so far: $result = mysql_query("SELECT * FROM user_table WHERE hash='$session_id'"); $rowuser = mysql_fetch_array($result); $result = mysql_query("SELECT * FROM products"); $rowproducts = mysql_fetch_array($result); So now I have $rowuser['gender'] = m , how do I remove all from $rowproducts where gender = f? Is there a best way to do this knowing I have about 20 points to go through before I am left with an array with just the best selection of products for this user in it?
- 4 replies
-
- array comparison
- arrays
-
(and 1 more)
Tagged with:
-
Newbie here, would love some help to find out what I'm doing wrong on this code. I'm using phpChart to make a graph. This is my code, but the graph does not appear. <?php require_once("phpChart_Lite/conf.php"); include 'connection.php'; ?> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>phpChart - Basic Chart</title> </head> <body> <?php $query = mysqli_query($con, "SELECT krl FROM diesel WHERE sted = 'Borgeskogen' ORDER BY dato ASC"); // set array $price = array(); // look through query while($row = mysqli_fetch_assoc($query)){ // add each row returned into an array $price[] = $row['krl']; } //$pc = new C_PhpChartX(array(array(11, 9, 5, 12, 14)),'basic_chart'); $pc = new C_PhpChartX(array($price),'basic_chart'); $pc->set_animate(true); $pc->draw(); ?> </body> </html>
-
Hello everyone! I am here to ask for some help with a certain script I have concocted. I run a moderately sized gaming community (using vBulletin 4.2.2) that supports multiple games, and as such we needed an automated roster to keep track of who plays what games. The code displays a list of games on the left, and the actual roster to the right. The default page is a "leadership roster" listing all the leaders. Game Roster pages include several things. Username, User Rank, IGN/Game Account Name, Join Date, and Last Active Date. You can sort by Join and Last Active Dates. There are also two types of members on the roster. Those who play the game as their "main game" and those who play it occasionally as an "other game". It is easy to get the main game members, since you can only have one, vBulletin saves it as text, so you can match it. The other games selector is saved bitwise, so we have to run a check for the game's location in the list against the user's saved bitwise in their profile to see if they play it. To do this, instead of manually coding the bit number, since everything is alphabetical, we simply assign each game a number, and do a a bitshift (1<<x) to get the proper bit (I've been told bitshift is much faster than using pow(2,x)). However, because it's specific too us, I have hard coded a lot of stuff, including mixing presentation code with functional code. The code works just fine for us, but I want to make it much easier so that other staff members besides me can update it easily and so the code is easier to manage. I hope I have given a good explanation of what the code does! To see the code in action, click http://www.zealotgaming.com/forum/pages.php?pageid=15 To see the code with syntax highlighted, here is the pastebin: http://pastebin.com/Nuanj4Ci I thank you all in advance for any help and advice you can give me. I am a novice and have been learning as I go to do this for my community.
-
Hi there i have recently started working with php so I will probably be a familiar name around here. I have been giving a task that I have got a bit stuck with. To give a brief overview I have products that are stocked in x number of warehouses, when a customer places an order depending on their location I will ship from the warehouse that is closest to them if it has all products in stock. I have the following two arrays The first represents a customers order containing the id of the product and the quantity they have selected. e.g. product id:35659, qty:1 Array ( [35659] => 1 [35699] => 1 [35734] => 2 ) The second array shows the quantity in stock for each product in each 3 warehouses that stock it e.g. 35659 being the product id, [9][114][126] being the warehouse and 10,1,0 being the quantity of stock for that item in the warehouse. Array ( [35659] => Array ( [9] => 10 [114] => 1 [126] => 0 ) [35699] => Array ( [9] => 8 [114] => 0 [126] => 5 ) [35734] => Array ( [9] => 10 [114] => 0 [126] => 0 ) ) function check_warehouse_stock($order=array(), $stock=array(), $warehouse=0) { foreach($order as $id => $qty) if($stock[$id][$warehouse] < $qty) return false; return true; } // $warehouses is an array of my warehouses already in their preference order foreach($warehouses as $w) { if(check_warehouse_stock($order, $stock, $w)) break; $w = false; } // $w is now the first warehouse with all the stock, or false if no warehouses have any stock So far I have got the above code which loops through each warehouse and goes into a function that checks each item in their order and sees if any item in their basket is below the quantity in the warehouse, if no items is below the quantity it returns true and that is the first warehouse with all items in stock, if no warehouse has all items in stock it returns false. This is where I am getting stuck, if no warehouse has all items in stock I need to go into a similar function and have some sort of rule that checks if no one warehouse has all products in stock I will ship from wherever has each product in stock starting with the closest and so on... e.g. if the first warehouse had 2 of the 3 items in stock and the second warehouse had 1 in stock we would ship 2 products from the first and 1 from the second. Any help would be greatly appreciated, even with just the logic on how to approach this. Thanks
-
Beginner here. Not sure why but I arrays are a huge source of frustration for me. I have this query: $query = $this->_db->getQuery ( true ); $query->select( 'a.table,a.places'); $query->from ( '#__tbb_reserves as a '); $query->where ( 'id = ' . $tid ); $this->_db->setQuery ( $query ); $myarray =$this->_db->loadRowList(); resulting in this array array { [0]=array { [0]= "9" [1]="10" } [1]= array { [0]= "5" [1]= "10" } [2]= array { [0]= "4" [1]= "6" } } From which I would like to create 2 new arrays: one from key [0] $array1 = array(9,5,4) and one from key [1] $array2 = array(10,10,6) Any help on how I would go about this is appreciated. Please let me know if I have left anything important out in my question. Also, if anyone knows of a good tutorial on the subject I would be very grateful.
-
I realized that my previous question wasn't clear enough so i decided to open a new thread (hopefully the old one will be removed - sorry for inconvinience). Here's my question - I got an extern html form that passes a value to some php file that is called makelist.php - The makelist.php simply analyzes the data that was sent through the $_POST method and puts all the 'right' values in one string array that is called $arrinfo - Each value there is a simple html snippet like '<a href=http://www.mywebsite.com/tes2t>testing</a>' . Now, assuming that i have an existing wordpress page which is called 'test1' for example - How can i put -all- that links (snippets) that exist in $arrinfo into a new sub page which will be like www.mywebsite.com/test1/arrinfolinks/ ? Do i need to install any wordpress plugin that will allow me to insert PHP code within posts/pages? Or is there any way to do it externally out of my php code? I can definitely put my php files in the same directory that wordpress uses so i can use wp_insert_post() for example - but i just couldn't figure yet how to create a sub page and insert all $arrinfo's content into it so it will be shown as links and not plain text of html tags.. thanks in advance..
-
Hi Guys, I have a very basic question that I cannot seem to answer ... so would appreciate any help / advise. Code snippet: $Text1="Hi, how are you"; $Text2="Hey there stranger"; $Text3="Its about time!"; $random_number = rand(1,3); $WelcomeText = "$"."Text".$random_number; echo $WelcomeText; The above script generates the output as $Text3 but what I am trying to achieve is this output: Its about time! I know I can use an array and output the value ... but I wanted to know -- why the above code would not work. Any help / explaination would be great! Thanks
-
I am NOT looking for max(). In an array, I'm trying to find the key with the highest value, not the highest value itself. For example, $arr = array(15, 10, 25, 419, 65, 25); echo max($arr); // Nope. Not what I'm looking for. Wrong answer. echoes the value 419. I know. Thanks. That's not what I want. We all know that in the above example, $arr[3]==419. I got that. But I am not looking for the 419. I'm looking for the 3. Thanks for any help.
-
Hi this is my first post after registering here. Please help me. I have a string of user data comma separated as below and pipe separated.I have been trying to remove duplicates by converting it to array. And even with php But it all does not works. My data looks like below: Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|2011-11-17|N/A|N/A|N/A|N/A|N/A|120, Santa_Roxburgh|bmw@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|10, Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|201-11-17|N/A|N/A|N/A|N/A|N/A|300, Saga_Shera|xyz@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|0, Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|120 I have tried What's the best way to remove duplicates from a string in PHP (or any language)?, detecting duplicate string in a explode function php and like this How to detect duplicate values in PHP array? one too. But none of these works in my case. Coz my data is not unique for same User say Marja_Roxburgh. I wants to remove all entries of Marja_Roxburgh based on its email but also wants to keep the first one only and sum all amounts from its transactions. I've been googling for any logic Im not able to understand what to do this it. How Do I keep only first Record of Marja_Roxburgh and remove all other of her. And also sum all her Amounts before removing her data? I'm missing the logic to understand and solve this problem. Can somebody help me understand this logic? any Ideas? Thanks
-
Hello, I am fairly novice at PHP. I have a couple of reference books*, but they seem to be vague on the subject of "arrays", that is why I am asking for help today. I am trying to create a simple array using a form and radio button selectors. At the bottom I will explain what I am trying to accomplish. Here is the sample of my code using one question: HTML........................................................................................................................................................................................ <fieldset> <legend>DO YOU EXERCISE DAILY?</legend> <form action="" method="post" /> <label for="question" class="question">I often exercise on a daily basis for at least 20 minutes a day</label> <label for "Never" class="radio"> <input type="radio" name="answer[0]=1" value="Never" /> Never</label> <label for="Seldom" class="radio"> <input type="radio" name="answer[1]=2" value="Seldom" /> Seldom</label> <label for="Occasionally" class="radio"> <input type="radio" name="answer[2]=3" value="Occasionally" /> Occasionally</label> <label for="Often" class="radio"> <input type="radio" name="answer[3]=4" value="Often" /> Often</label> <label for="Always" class="radio"> <input type="radio" name="answer[4]=5" value="Always" /> Always</label> </form> </fieldset> When a question is asked, the user can choose only one (radio button) answer. That answer is assigned a number (1 thru 5) and will be displayed and then eventually tallied along with answers to other questions (not shown) for a grand total or sum. PHP.......................................................................................................................................................................................... <?php //Error Displaying ini_set ('display_errors',1); error_reporting (E_ALL & ~E_NOTICE); //Print each answer <?php if (isset($_POST["answer"]) && is_array($_POST["answer"]) && count($_POST["answer"]) > 0) { foreach ($_POST["answer"] as $answer) { echo htmlspecialchars($answer, ENT_QUOTES); echo '<br />'; } } ?> // Print each key and value. <?php $answer = array ('Never', 'Seldom', 'Occasionally', 'Often', 'Always'); foreach ($answer as $ans => $answer) { print "$ans: $answer<br />\n"; } ?> I am able to get the answer (picked via radio button) to print or echo on the page, but I am not sure how to display a number represting each choice (1 for Never ~ 5 for Always). Not sure what I am doing wrong. I have researched other examples on the web and tried their logic, still no success. I guess I am just not getting it. Any advice or help would be appreciated. Also do any of you readers recommend another book to learn from? Signed, Garfan *Murachs PHP and MYSQL *PHP For The World Wide Web by Larry Ullman
- 5 replies
-
- phpradio buttons
- form
-
(and 1 more)
Tagged with: