PHP - Array_push() Not Adding Anything To Array
I am trying to add new elements to an empty array using a form and submit button and the code is not adding anything from it. Here is the code I use:
<!DOCTYPE html> <html> <head> <title> </title> </head> <body> <div class="site"> <div class="menu"> </div> <div class="head"> </div> <div class="content"> <form> <input type="text" value="" name="add"/><br/> <input type="submit" value="Add" name="submit"/> </form> </div> <div class="footer"> </div> </div> </body> </html> <?php $submit = $_POST["submit"]; $field = $_POST["add"]; $list = array(); if($submit){ $psh = array_push($list,$field); echo $list; } ?>Any idea why is it not working? Similar TutorialsHello all. I'm pretty new to this, but I'm trying to build a script that will write random questions for a quiz app that I'm working on. The data is contained in two different tables. I'm trying to randomize the question order that is spit out, as well as randomize the answer order that is displayed. The output has to be in the specific JSON string that is denoted in the code. There are no errors when I go the url that I load the script, however, the string is not populated with any of the data from my tables (it is just an empty set of strings in the JSON format that the program requires. Could someone please take a look at this and tell me where I'm going wrong. I've checked that the query is pulling from the correct databases so I know that's not the problem. Thank you in advance. Code: [Select] <?php //Connect To Database $hostname=""; $username=""; $password=""; $dbname=""; $question_table="wp_mtouchquiz_question"; $answer_table="wp_mtouchquiz_answer"; $yourfield = "question"; $question = "question"; $answer = "answer"; $connection = mysql_connect($hostname, $username, $password); $lastQuestionID = -1; $str = ""; mysql_select_db($dbname, $connection); # Check If Record Exists $query = "SELECT * FROM $question_table q, $answer_table a WHERE q.ID = a.QUESTION_ID AND q.quiz_id = 1 ORDER BY question_id ASC, correct DESC"; $result = mysql_query($query); $questions = array(); $fields = array(); if($result) { while($row = mysql_fetch_array($result)) { if($lastQuestionID != $row["question_id"]) { $fields = array(); if($lastQuestionID != -1) { array_push($questions, $fields); } $fields = array(); $lastQuestionID = $row["question_id"]; $fields["question_id"] = $row["question_id"]; $fields["question"] = $row["question"]; } // correct if($row["correct"] == 1) { $fields["correct"] = $row["answer"]; } // incorrect if ($row["sort_order"] ==2) { $fields["incorrect0"] = $row["answer"]; } // incorrect if ($row["sort_order"] ==3) { $fields["incorrect1"] = $row["answer"]; } // incorrect if ($row["sort_order"] ==4) { $fields["incorrect2"] = $row["answer"]; } if ($row["sort_order"] ==5) { $fields["incorrect3"] = $row["answer"]; } } $str .= "{\"childItems\":["; $numQuestionsToUse = 172; //Set this larger than returned questions or less than row limit / 5 $randomQuestionKeys = array_rand($questions, $numQuestionsToUse); $numQuestions = count($randomQuestionKeys); for($i = 0; $i < $numQuestions ; $i++){ $pickedField = $questions[$randomQuestionKeys[$i]]; $str .= "{\"itemId\":\"question" . $pickedField["question_id"] . "\","; $str .= "\"itemType\":\"BT_questionItem\","; $str .= "\"questionText\":\"" . $pickedField["question"] . "\","; $str .= "\"correctAnswerText\":\"" . $pickedField["answer"] . "\","; $incorrectAnswers = array(); array_push($incorrectAnswers, $pickedField["incorrect0"]); array_push($incorrectAnswers, $pickedField["incorrect1"]); array_push($incorrectAnswers, $pickedField["incorrect2"]); array_push($incorrectAnswers, $pickedField["incorrect3"]); $incorrectAnsKey = array_rand($incorrectAnswers, 3); $str .= "\"incorrectText1\":\"" . $incorrectAnswers[$incorrectAnsKey[0]] . "\","; $str .= "\"incorrectText2\":\"" . $incorrectAnswers[$incorrectAnsKey[0]] . "\","; $str .= "\"incorrectText3\":\"" . $incorrectAnswers[$incorrectAnsKey[0]] . "\","; $str .= "\"imageURLSmallDevice\":\"http://www.myquizcoach.com/extras/images/clear_header.png\","; $str .= "\"imageURLLargeDevice\":\"http://www.myquizcoach.com/extras/images/clear_header.png\"},"; } // remove last comma $str = substr($str,'',-1); $str .= "] }"; echo $str; } ?> Hey guys I have the following script that correctly retrieves 2 values from mysql: security_code and selected_address: The problem I have, is how can I add the retrieved values (more than 1 row) inside an array called $data $data = array(); $result = mysql_query("SELECT security_code, selected_address FROM purchase WHERE purchase_id = '412012' AND selected_address = 'General Roca 900' ORDER BY `offers_bought`.`security_code` ASC"); $cant = 0; while($row=mysql_fetch_array($result)) { array_push($data[$row['selected_address']], $row['security_code']); $cant++; } The array_push function gives me the following error: Warning: array_push() [function.array-push]: First argument should be an array in C:\wamp\www\Test\test\excelTest.php on line 24 In other words this is want I want to achieve: $data = array(array("selected_address" => $row['security_code'])); Only that this example adds only 1 retrieved row Any ideas? Thanks in advance! Cheers, Our disc golf league uses a little PHP script that I developed (stealing lots of code in the process) that sucks in a list of league players from a text file, lets you select the ones that show up on league day, and randomly assigns the selections into foursomes and threesomes (Demo: http://edge.byethost18.com/demo4/foursomes.php)
Here's a modified example using letters of the alphabet:
. . . and the code: The actual version uses the shuffle() function to randomize the assignments and has a refresh button to reshuffle the assignments if a grouping contains bitter enemies. I disabled it in the example in order to show how the "A-B-C"s are assigned to the groups. As you can see, it assigns "A" to the first group, "B" to the second group, "C" to the third group and so on until it reaches the last group and then starts back at group 1 with the next letter. One of the our players wants a modification. He wants to be able to assign players into foursomes/threesomes according to their handicaps (best to worst). In other words, Group 1 would contain A, B, C, D. Group 2 would contain E, F, G, H and so on. Naturally, this would depend on which player checkboxes are selected, but the order is maintained. What I am having trouble with is getting the "A-B-C"s assigned into groups in the order they are listed in the text file. I tried using array_chunk() in the following script: https://neth.roe3.org/mdrone/ABCs/foursomes2.php
. . . and the code: In a nutshell, here's the code that's doing the work . . .
$numgroups = $d; $rows = array_chunk($players,$numgroups);
$x=0; I'm sure there's a simple solution. I'm just not seeing it. I'm really just a hobbyist . . . not a real programmer by any stretch of the imagination. Thanks for any help anyone can send my way. BTW . . . if anyone is interested in the foursomes generator source, I'm happy to share it. It could probably use improvement. Using curl_multi, I have loaded up 3 url's and then printed the array. 1) How can I also set a timestamp on output to let me know when each url was run? 2) How can I explode the array to only display the data and timestamp, excluding the text "Array ( =>", "[1] =>", "[2] =>" and " )"? Code <?php function multiRequest($data, $options = array()) { // array of curl handles $curly = array(); // data to be returned $result = array(); // multi handle $mh = curl_multi_init(); // loop through $data and create curl handles // then add them to the multi-handle foreach ($data as $id => $d) { $curly[$id] = curl_init(); $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d; curl_setopt($curly[$id], CURLOPT_URL, $url); curl_setopt($curly[$id], CURLOPT_HEADER, 0); curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1); // post? if (is_array($d)) { if (!empty($d['post'])) { curl_setopt($curly[$id], CURLOPT_POST, 1); curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']); } } // extra options? if (!empty($options)) { curl_setopt_array($curly[$id], $options); } curl_multi_add_handle($mh, $curly[$id]); } // execute the handles $running = null; do { curl_multi_exec($mh, $running); } while($running > 0); // get content and remove handles foreach($curly as $id => $c) { $result[$id] = curl_multi_getcontent($c); curl_multi_remove_handle($mh, $c); } // all done curl_multi_close($mh); return $result; } $data = array(array(),array()); $data[0]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Pearl+Jam&output=json'; $data[1]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Black+Eyed+Peas&output=json'; $data[2]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Nirvana&output=json'; $r = multiRequest($data); print_r($r); ?> Output Array ( => Pearl Jam [1] => Black Eyed Peas [2] => Nirvana ) Preferred Output 01:00:01 Pearl Jam 01:00:02 Black Eyed Peas 01:00:03 Nirvana So I'm querying my database to add the results (mapID's) into a PHP array. The MySQL query I used in the below code would usually return 10 values (only 10 mapID's in the database) Code: [Select] while($data = mysql_fetch_array(mysql_query("SELECT mapID FROM maps"))){ $sqlsearchdata[] = $data['mapID']; } Instead the page takes ages to load then gives this error: Quote Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 16 bytes) It says the error begins on the first line of the above code. I'm assuming this is not the right way to add the value from the MySQL array into a normal PHP array. Can anyone help me? from what i understand from the coding... $form->getField('uri') is for the Sql table field (field uri) location and ->getValue() is the inputbox Value so ->setUri is grabbing the inputbox value and inserting it into Field 'uri' but what I need to do is combine getValue with the string/url profile.site.com/file?name= Code: [Select] $new_uri ->setUri($form->getField('uri')->getValue()) ->setHost($form->getField('host')->getValue()) ->setUser($user->isAuthorized() ? $user->getId() : 0) ->save(); Here's the code: Code: [Select] $year_values = array('Any', 'N/A', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012'); $db_year = explode(', ', $row['YEAR']); foreach($year_values as $year_value) { $selected_year = null; $year_label = $year_value; if(in_array($year_value, $db_year)) { $selected_year = ' checked="checked"'; $year_label = "<b>$year_value</b>"; } echo '<input type="checkbox" name="year" value="' . $year_value . '"' . $selected_year . ' />' . $year_label . ' '; } ?> [/code That pulls the data of the database and puts it in check boxes. The user can check/uncheck certain boxes but the problem is when it goes to the verify page it has only one value from the array that was selected. On the verify page it just checks if a box was checked and then implodes the array before submitting it into the database. [code] $year_s=implode($year,", "); So like I said there is only one value from the array when there should be as many as the user checks. So basically I believe the value isn't added to the array. I've got a site running, and I would like to add up the totals from each location to one number, now I know it can be done, I just don't know how it'll work with my current code (see below) <table summary="" border="1" width="1100"> <tr> <td>Date</td> <!-- <td>Employee</td> --> <td>Store</td> <td>Customers</td> <td>Quotes</td> <td>Phone Calls</td> <td>Services In</td> <td>Services Out</td> <td>Invoices</td> <td>Conversion</td> <td>End of Day</td> <td>Emails</td> <td colspan=3>Notes</td> </tr> <? $x = 1; $y=1; $lastdate=0; while ($list = mysql_fetch_assoc($query)) { $dateadd = $list['dateadd']; $dateb = strtotime($list['dateadd']); $date = date("M j Y", $dateb);$date2 = date("Y-m-d", $dateb); $firstname = $list['firstname'];$lastname = $list['lastname'];$store = $list['store'];$customers = $list['cust'];$sales = $list['sales'];$invoices = $list['invoices'];$sin = $list['servin'];$sout = $list['servout'];$eod = $list['eod']; $phone = $list['phone']; $notes = $list['notes']; $emails = $list['emails']; if ($store == "1") {$storename = "Broadmead";} elseif ($store == "2") {$storename = "Duncan";} elseif ($store == "3") {$storename = "Surrey";} elseif ($store == "4") {$storename = "Sooke";} elseif ($store == "5") {$storename = "Nanaimo";} elseif ($store == "6") {$storename = "Shelbourne";} ?> <?php if ($lastdate == $date) { ?> <tr> <td width="125"><?=$date;?></td> <!-- <td width="125"><?=$firstname;?> <?=$lastname;?></td> --> <td width="100"><?=$storename;?></td> <td width="71"><?=$customers;?></td> <td width="71"><?=$sales;?></td> <td width="80"><?=$phone;?></td> <td width="80"><?=$sin;?></td> <td width="90"><?=$sout;?></td> <td width="71"><?=$invoices;?></td> <td width="71"><? $convbase = $sout+$sales; if (!$invoices==0 && !$customers==0) {$conv = $invoices / $customers * 100;} else {$conv=0;} echo money_format('%(#1n', $conv) . "\n"; ?>%</td> <td width="71">$<?echo money_format('%(#1n', $eod) . ""; ?><td> <td width="71"><?=$emails;?> </td> <td width="150"><?if (!$notes==NULL){echo $notes;} else {echo " ";}?></td> </tr> <?php } else { ?> <tr> <td colspan="9">Daily Total</td> <td><?echo money_format('%(#1n', $total) . ""; ?> </td> <td colspan="4"> </td> </tr> </table> <hr width="1100" align="left" color="0000ff"> <table summary="" border="1" width="1100"> <tr> <td width="125"><?=$date;?></td> <!-- <td width="125"><?=$firstname;?> <?=$lastname;?></td> --> <td width="100"><?=$storename;?></td> <td width="71"><?=$customers;?></td> <td width="71"><?=$sales;?></td> <td width="80"><?=$phone;?></td> <td width="80"><?=$sin;?></td> <td width="90"><?=$sout;?></td> <td width="71"><?=$invoices;?></td> <td width="71"><? $convbase = $sout+$sales; if (!$invoices==0 && !$customers==0) {$conv = $invoices / $customers * 100;} else {$conv=0;} echo money_format('%(#1n', $conv) . "\n"; ?>%</td> <td width="71">$<?echo money_format('%(#1n', $eod) . ""; ?><td> <td width="71"><?=$emails;?> </td> <td width="150"><?if (!$notes==NULL){echo $notes;} else {echo " ";}?></td> </tr> <?php } $lastdate = $date; } // end while ?> </table> Any help would be appreciated. i need help with adding an integer into an array something like this $Loaded[count($Loaded)+1] = $To; Hi I currently pass a URL to our website as follows: http://website.com/?nid=10 but want to extend this to include a keyword from google as well. For example http://website.com/?nid=10&kw={keyword}. However it may not always have a keyword so if it does not it needs to just use the nid array. This is the current script, how do I go about changing it so that if it just contains a nid and no keyword it will do one search of the array and return the result, and if it does have a nid&keywordod it returns something different. For example if it had nid=1 it would return 0844 000 0300 and if it had nid=1&kw=help it would return 0844 000 0350 Thats what I am looking to achieve. Is this possible and how do I change the array. I have had a little attempt but not sure what I am doing and just got coding errors. <?php $GLOBALS['ct_get_parameter_name'] = 'nid'; $GLOBALS['ct_default_number_id'] = 0; // source_id => phone number $GLOBALS['numbers'] = array( 0 => '0844 000 3000', 1 => '0844 000 0300', 2 => '0844 000 0301', 3 => '0844 000 0302', ); session_start(); if (array_key_exists($GLOBALS['ct_get_parameter_name'], $_REQUEST)) { $_SESSION['ct_source'] = $_REQUEST[$GLOBALS['ct_get_parameter_name']]; } function get_phone_number() { $numbers =& $GLOBALS['numbers']; $default_number_id = $GLOBALS['ct_default_number_id']; if (isset($_SESSION['ct_source'])) { if (array_key_exists($_SESSION['ct_source'], $numbers)) { return $numbers[$_SESSION['ct_source']]; } else { // otherwise return first number return $numbers[$default_number_id]; } } else { // return first number return $numbers[$default_number_id]; } } ?> Many thanks in advance. Roy I have an array of products. The array has an ID and price. I'd like to know the most efficient way of adding up all the same ID fields in the array. Code: [Select] <?php $items[] = array( 'id' => 1, 'price' => 5.99, ); $items[] = array( 'id' => 2, 'price' => 1.99, ); $items[] = array( 'id' => 3, 'price' => 2.40, ); $items[] = array( 'id' => 2, 'price' => 6.99, ); $items[] = array( 'id' => 4, 'price' => 8, ); $items[] = array( 'id' => 2, 'price' => 3, ); $items[] = array( 'id' => 3, 'price' => 1, ); function add_like_items($items) { //manipulation return $sums; } //$sums would be an array like //$sum[1] = 5.99 //$sum[2] = 11.98 //$sum[3] = 3.40 //$sum[4] = 8 ?> Anybody have suggestions on the best way to go about doing this? Hi im having some trouble when i try to add values to an array from a function. The added value will not stay saved. fun1 will display both firstname and surname but when i call fun2 after calling fun1 i just get the firstname. I would like to have it so the array is updated and stays updated untill it is cleared or over written. Any help with this would be greatly appreciated. i am using codeigniter if that makes any difference. Thanks <?php class Test extends Controller { var $data1 = array( 'firstname' => 'craig' ); function fun1() { global $data1; $this->data1['surname'] = 'brute'; echo "<pre>"; print_r($this->data1); } function fun2() { global $data1; echo "<pre>"; print_r($this->data1); } } I have the following multidimensional array where each sub-array represents quantity[0] and item #[1]: Array ( => Array ( => 1 [1] => 12113 ) [1] => Array ( => 2 [1] => 21200 ) [2] => Array ( => 4 [1] => 10200 ) [3] => Array ( => 1 [1] => yyyy ) [4] => Array ( => 20 [1] => xxxxx ) [5] => Array ( => 5 [1] => 21200 ) I'm trying to consolidate like items. For example I need to create a new array that reflects any duplicate part numbers with a combined quantity. (ie. ... => 7 [1] => 21200 ... hello, how would i add the values off all results in the $pamount array? Code: [Select] $result2 = mysql_query("SELECT * FROM pobook WHERE jobnumber = '$jobid'"); while($row2 = mysql_fetch_array($result2)) { $pamount=$row2['amount']; echo "<tr>"; echo "<td>" . $pamount . "</td>"; echo "</tr>"; echo "<tr>"; echo "<td>VALUE OF ALL RETURNED $pamount HERE</td>"; echo "</tr>"; Hi everyone, Hope someone can help. Does anyone know why this is nor displaying any data? Code: [Select] $qry = mysql_query("select * from product"); $data = array(); while($row = mysql_fetch_array($qry)){ $productName[] =$row['productName']; // Item name } for($i=0;$i<mysql_num_rows($row);$i++) { $data = $productName[$i]; } return $data; Thanks in advance Edd Hey guys: If I some multi-dimensional arrays, like so: Code: [Select] array { array { [0]=> "Path1" [1]=> "10" } } array { array { [0]=> "Path2" [1]=> "16" } array { [0]=> "Path3" [1]=> "110" } } How can I add all of the values of key 1? I know its a foreach loop, but I can't figure it out... would it be this? I have a file containing lines (I mean elements separated by <br>). How I can put these lines into an array, but only those which has a given phrase. Example file Code: [Select] This is the first line<br> Second line is here<br> something else<br> something else<br> something more<br> I want to catch only lines which contain the word "something" and make an array. I have created a session array on one page and stored some values as $_SESSION['users'] = array( "id" => $row['id'], "fname" => $row['ufname'], "lname" => $row['ulname'] ); and then on another page I have some more values for the same session array "boss" => $row['bossid'], "tasks" => $row['tasks'], "timeframe" => $row['tframe'] I want to add these values into session array both keys and values. is there any way of doing this? Please help Hi all, I'm trying to write a function to return an array. But it keeps returning an empty array with NULL values .... This is my code. function ShowUserData ($uid) { $con = mysql_connect("localhost","user","pass"); if (!$con) { die('Oops !! something went wrong with the DB connection, Server said ' . mysql_error()); } mysql_select_db("db", $con); $password = md5($password); $query = mysql_query("SELECT * FROM `table` WHERE `uid` = '".$uid."'"); $num = mysql_num_rows($query); while ($row = mysql_fetch_array($query, MYSQL_NUM)) { $outArray = array('uid' =>$row['uid'], 'email' => $row['email'], 'name' => $row['name']); } return $outArray; } what am i doing wrong? |