Array Append
How may I programatically append and create the following predefined
array in PHP?
Although the example has all the data and the subsequent arraw
predifined I must create an array while iterating through the rows in an
RDBMS.
array(
array('name' => 'bob', 'phone' => óS-3425'),
array('name' => 'jim', 'phone' => óS-4364'),
array('name' => 'joe', 'phone' => óS-3422'),
array('name' => 'jerry', 'phone' => óS-4973'),
array('name' => 'fred', 'phone' => óS-3235')
)
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Append To String
I've got 3 variables in a form: products[], ib, wl. products[] contains whichever values where checked from about 20 checkboxes, and the other two (ib, wl) are either "yes" or "no". The reason for this is that there is a limit of 4 products to order, except for ib/wl which don't count as part of the 4. Now, want the values to be sent by e-mail: "Products: ql, ba, wl". I did [b]$prod = implode (",",$products);[b], and then I would like to append ", wl" to $prod IF the value is "yes" and also ", ib" if the value is "yes". How would I do that? Thanks!
Header Append Question
I am trying to avoid using frames when people click on my links section to see other sites outside of my site, but I don't want to have them leave in a new window. Sort of the way that yahoo shopping works where it can bring in other sites, like KMart, Jcrew etc. and have the yahoo header on top of them but all be in the same scrollable page. How is this done? My problem thus far has been that if I put my header on let's say Kmart's site. The minute someone clicks a link in the kmart page I can't still have my header there, but Yahoo can?
How To Append A Child Dynamically
i m new in both things php and in this group. but i have some basic knowledge of php and DOM in php. here is my problem, i have one textfield for add a new main node (not main like: <root><this_one></this_one></root>) in my php page and i m able to save the xml file correct with this, and in the bottom of that i have one new textfield for add new child in dynamically create node (which i descibe above),and one combo box for show the all dynamically create nodes.now i want that when user give the value in child textfield and then select a root node for that child from combo box.i want to append a child dynamically to root node. but i m not able to do this. plz try to solve my prob...
Treemenu Append Automatically
Here i got a problem to append my treemenu file automatically. this mean that the user haven't need to click the main title of menu to display their subtitle(allow the user to done other funtions on it).
Loop Through And Append To String
The following code: for ($i = 0; $i < $varcount; $i = $i + 1) {echo "," . "$parts[$i]";} Will output: ,$parts[0],$parts[1],$parts[2],$parts[3],$parts[4],$parts[5],$parts[6],$parts[7],$parts[8] What is a good way to append or save the resulting output to a variable?
Append Two Textfields Into A Third One With A Space
i dont know if its a stupid question but im so new to php you can forgive me well the thing is i have 3 text fields textfield1 textfield2 textfield3 I want to add textfield 1 with textfield 2 and display it in a hidden textfield3 with a space between the text. Textfield1(Sam) + Textfield2(Yam) = Textfield3 (Sam Yam)
Append To A Temporary File?
Is it possible to append to a temporary file? I'm iterating through a file and when a condition becomes true, I want to append the content to a temporary file. I want to display the contents once the loop completes. If there's a better suggestion on how to go about this, please let me know.
DOM XML - How To Append A Link Element As A Child
I'm trying to generate a RSS newsfeed using the DOM XML functions, but you already know that if you read my previous post . I'm able to create rss, channel and title elements but not a link element. The following code sample doesn't generated <link>http://www.websitetitle.com</link> but <link> like if the DOM XML forgot to close the element : <?php $link_el = $dom_doc->create_element ('link'); $link_el = $channel_el->append_child ($link_el); $link_el->set_content ('http://www.websitetitle.com'); ?> Then I got some crazy idea. I thought that maybe DOM XML was thinking the link element I created was a specially element, not an enclosed one, like in XHTML for example : <link rel="stylesheet" type="text/css" href="styles.css" /> Crazy crazy because I don't see why DOM XML would handle my elements as HTML elements... But then I tried with a meta tag, and guess what... It also doesn't work ! It works with enclosed elements, tags, like title, head, html, body or unknown ones like channel or item. But it doesn't work with link, meta and input elements ! And I have no clue why it handles these elements as special elements... Here is the full script :
Error Check Before Append To File.
I want to be able to append my httpd.conf file from a web browser to make adding virtual hosts a little easier. I've got a simple form that passes two variables. $virtualhost and $subdirectory. what I want to be able to do is read the file and make sure that there is not already a domain name and subdirectory in the file. Code:
Fopen - Append Works, Write Fails (but File Is Truncated)
I'm trying to write to a file in the current directory - no remote files. The subject says it all - I can add that both the directory and the file is wordwritable. This happens on a (quite good) free hoster in Norway which doesn't use safe mode, running PHP 5.1.6 as the PHP info below shows ... Test it at: http://home.no.net/moldevbk/fopen-test/?mode=w (write - fails) http://home.no.net/moldevbk/fopen-test/?mode=a (append - ok) http://home.no.net/moldevbk/fopen-test/p.php - PHP info http://home.no.net/moldevbk/fopen-test/fopen-test.phps - source code of test script. I have searched the web and usenet, but not found this problem mentioned before. I do realize that I can work around the problem by truncating the file first and then appending to the empty file - but that is ugly as ...
Append "string" To Uniqe ID?
Hi, I'm using a this to generate a unique ID: $id = (substr(uniqid (""), 2, 7)); example output >> c846dd1 I'd like to append "abc" to beginning of the id. eg. abcc84dd1
Append Text At End Of Existing Text On Same Line
I'm working on a part of my web site that uploads images, then writes the name of the image to a text file. The upload part works fine. The part that writes the name of the image to the text file works fine. What I'm trying to do is, after all the files have been uploaded and all of the image names have been written to the WriteTo.txt file, append a written description of the picture at the end of the picture name. In other words, after a user uploads their pictures to the server I want to direct them to a page where they can label each of the pictures using a form. PHP Code:
Selecting Array Rows Based On An Array Of Field=>values
Here's the code i have: $db = array(); //main array $db['main'] = array(); //table `main` $db['main'][] = array('id'=>0, 'username'=>'joshfrench','userpass'=>'password','userlevel'=>'admin'); //row $db['main'][] = array('id'=>1, 'username'=>'bob_smith','userpass'=>'psswrd','userlevel'=>'user'); //row function trim_value(&$value){ $value = strtolower(trim($value)); } function fdb_select($fields = "*", $table, $where = false, $limit = false){ global $db; $retv = $db[$table]; //LIMIT RESULTS TO FIELDS if(strrpos($fields, ",") === false){$field=array($fields);}else{$field = explode(",", $fields);}; array_walk($field, "trim_value"); $all_fields = array_keys($retv[0]); if($fields == '*'|| is_null($fields)){$field = $all_fields;}; $field = array_uintersect($all_fields, $field, "strcasecmp"); $retvi = array(); foreach($retv as $num =$row){ foreach($row as $fname =$fvalue){ $fname1 = strtolower($fname); if(in_array($fname1, $field)){ $retvi[$num][$fname]=$fvalue; }; }; }; //DONE LIMITING TO FIELDS if($where != false){ //UP TO HERE IT WORKS FINE //LIMIT TO WHERE CLAUSE $retvj = array(); foreach($retvi as $num =$row){ //IN THE ROW foreach($where as $k =$v){ //IF ROW MEETS ALL REQUIREMENTS if($row[$k] == $v){ $retvj[] = $retvi[$num]; //Keep that row }; }; }; //DONE LIMITING TO WHERE CLAUSE }; $retvi = (isset($retvj)) ? $retvj:$retvi; //SEND A FINAL ASSOCIATIVE ARRAY return $retvi; }; print_r(fdb_select("*", "main", array('id'=>"1", "username"=>"joshfrench"))); the previous code outputs this: Array ( [0] =Array ( [id] =0 [username] =joshfrench [userpass] =password [userlevel] =admin ) [1] =Array ( [id] =1 [username] =bob_smith [userpass] =psswrd [userlevel] =user ) )
Multidimensional Array Syntaxt For Preg_split Array Using Submitted Textarea
I have two textarea's called textarea1 and textarea2. What i did was use preg_split to split the textarea into seperate rows that i could use for analysis like so $array = preg_split("/[ ]?[ ]/", $_POST['textarea2'], -1,PREG_SPLIT_NO_EMPTY); $array2 = preg_split("/[ ]?[ ]/", $_POST['textarea1'], -1, PREG_SPLIT_NO_EMPTY); then i used a function created for me by a nice guy on here called get_ending($filepath) which basically stripped off of each peice of text the "http://www" from every URL i put into the textareas finishing off i wanted to create an array that would input an expression such as: echo "<a href='$array[1]' target='_blank'><img src='$array2[1]' border='0'>"; into a text area on the next page. ALL of this works, except that i dont know how to properly loop throught he array so it'll properly insert the text into the textarea on the next page. For now, all it does is place the array information in the page, rather statically, i would like to run some kind of if then statement that says "while $array has some kind of text in it, keep running this operation of echoing the following expression adding 1 to the end of the array number" I hope that makes sense Any ideas? Code:
Finding Elements Of An Array In Another Multi-dimensional Array
So I have 2 arrays: one contains userids. It may look like: user_id[0] =12, user_id[1] =30, user_id[2] =43 The other is a multi-dimensional array with fields like: user_info [0] = Array ( [user_id] =13 [user_flag] =1 [url] =http://www.example.com?index,0 ) user_info[1] =Array { Array ( [user_id] =120 [user_flag] =1 [address] =1234 Main St, Anytown, USA [url] =http://www.yahoo.com ) user_info[2] =Array { Array ( [user_id] =130 [user_flag] =1 [address] =134 Main St, Anytown, USA [url] =http://www.google.com )
Sorting An Array Problem, (array/string Manipulation)
I have a function that I found on google, that goes through a directory and spits out a directory tree in an array, with arrays inside of arrays, and more and more arrays inside of arrays, depending on how many subdirectories are there..... Here is a sample "directory tree" it spits out. My problem is wanting to be able to create a new array containing only the paths to all the subdirectories it finds from this array, so it is with array manipulation... Not all paths are located in the topmost array's values, but some directories are within other subdirectories and so forth.. I'm stumped on how exactly to sort through this array, whether recursively or not to grab all the 'paths' in the array period. Code:
Sorting Sql Results In An Array Using Things Outside The Array To Sort Them?
I'm using PHP to connect to a database full of place names, and their associated post codes, latitude and longitude on the earth. A user types his or her post code into a form, plus a distance (in miles), and the script looks for other area codes (first half of the post code) within that distance. I can do that fine, but the results are ordered alphabetically by postcode, and I want to order it by the distance. Problem here, is that the distance isn't part of the array taken from the database, it takes the latitude and longitude of the area it's on in the while loop, and calculates the distance between the user's post code and that one, but it's not part of the array, so I can't sort the array using it. How can I sort it? Can I add the calculated distances to the array, and sort it using sort()? If yes, how do I add them to the array? Here's the page, just to explain better what the script does: http://navimaker.org/ed/owain/results.php?postcode=gl15&distance=34 Mess around with the postcode and distance vars. I'd put the source on here too but I'm doing all this over SSH and can't copy & paste very easily .
Array Checking For Page Content In A Array
i am using a function which gets all the links from a page, from that i have a function that gathers the html in the page from each links..this part works great.. i then need to check and see if it has a applet, flashmovie etc tag in the page. if there is a tag like this in the page ineed to return true if there isnt i need to return false i have provided code thats shows how i gather the links echo them out and checks to see if certain html tags are in a page using a function $snoopy->fetchlinks($url); $results=$snoopy->results; $results=array_unique($results); sort($results); for($i=0;$i < $numberoflinks; $i++) { $results[$i] = preg_replace( "/(?<!")((http|ftp)+(s)?://[^<>s]+)/i", "", $results[$i] ); if ($results[$i] == '') { } else { ?> <a href="index.php?mode=2&url=<? echo $url.$results[$i];?>"><? echo $results[$i];?></a> <? $snoopy->fetchform("$url.$results[$i]"); $test=$snoopy->results; / if($test != "") { echo "problems seen<br>"; }else{ echo "no problems<br>"; } } }
Array Sorting Blues....2 Dimensional Array
I have a 2 dimensional array where one col contains a Unix style date and the other contains a filename. I read through a directory to get this info. I can load the array and print it out just fine, but I can't seem to sort it using any of the sort functions! I want to reverse sort them, since they are news stories that I want to display in the correct order by date. When I try to sort I get a "Warning: Cannot compare arrays or objects" message. I have the feeling it's something stupid on my part but can't find any good examples anywhere. Anyone have an idea about this? P.S. I know a database would solve this but sadly it's not an option for me right now...
Turn Array Into Multi-dimensional Array?
How can I take an existing array and turn it into a multi-dimensional array? I want to get a single row out of a MySQL table and have it in an array, but have along side the values the true field (column) length for each of the fields from the table. Here's my stab at it: $userDetails = mysql_fetch_array($resultID); $i = 0; while ($i < mysql_num_fields($resultID)) { $userDetails[$i][2] = mysql_field_len($resultID, $i); $i++; } And I guess the follow up question (if this is indeed possible) is will this work with a multi-row return from the DB also?
Setting Variable To Array Within Mysql_query() Array
I found your site while attempting to solve the problem of utilizing JOIN statements in a PhP mysql_query. Your timely and well-structured assistance to LemonFizz was very helpful, and enabled me to develop the query below. I have now queried multiple tables to produce an associative array of all of a particular student's data after selecting the student's unique ID from a drop-down. This required the use of JOIN statements in my query. The query section of the file is as follows:
Create Array From Members Of An Array Of Objects
I have the following situation: $list[] is an array of MyElement objects. MyElement has two members: MyElement->member1; MyElement->member2; What I want is to get the following: $newlist[] so that: $newlist[0]=$list[0]->member2; $newlist[1]=$list[1]->member2; $newlist[2]=$list[2]->member2; .... I need to do this using A SINGLE LINE OF CODE. Is it possible? How to do this? I tried with: array_walk($list,create_function('$a,$b,$result',' $result[] = $a->member2;'), &$result); but I get the following error: Warning: Call-time pass-by-reference has been deprecated - argument passed by value; If you would like to pass it by reference, modify the declaration of array_walk(). If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file. However, future versions may not support this any longer.
Trying To Calculate An Average Array From An 2d Data Array
I'm trying to calculate an average array from an 2d data array. my problem is that my function does not generate an average array but just one value. but i do not understand why it does not work. code: ----- function calculateAverageRating($rating_matrix) { $average_rating = array(); foreach($rating_matrix as $cus_id => $ratings) { $counter = 0; $sum = 0; foreach($ratings as $pro_id => $item_rate) { $counter++; $sum += $item_rate; } echo $cus_id."->".($sum/$counter)."<br>"; $average_rating[$cus_id] = ($sum / $counter); } echo "<hr>"; echo "<table> <tr>"; foreach($average_rating as $key => $value); { echo "<td>$key::$value</td>"; } echo "</tr></table>"; return $average_rating; } wanted: input -> output 1 1 1 1 2 2 2 2 4 4 4 4 but my functions just does: input -> output 1 1 1 2 2 2 4 4 4 4
Passing Array Of Multidimensional Array To Function
How do I pass a part of a multidimensional array to a function. I have the following (in pseudo): $arrays[m][n]; // filled with values $chosen = 3; function doSomething($array) { // do something with 1D array } This fails: doSomething($arrays[$chosen]); Can someone explain to me why? And how to do this right?
Getting Array Information Out Of A Function On Into Another Array
I need to find a way to transfer all the values of an array inside a function out of the fuction into another array. IE function splice($filename){ if(file_exists($filename)){ $value=array("0"); // clear the array. $rows=file($filename); // break text file into a rows array for($num=0;$num < count($rows); ++$num){ $column=split(";",$rows[$num]); $value[$num]=$column;}} return $value; } $array1 = splice(file.txt) Example file data would be data1;an1;bc1 data2;an2;bc2 data3;an3;bc3
Creating An Array Of Two Elements From Another Array
I’m trying to create an array that contains a department name and a associated colour code, by filtering from a SQL result. I’ve written a simple script, but to be honest I’m now stumped how to create such an array. PHP Code:
Set An Array Of Array, Do An Unset And Display Both
see this code, i only set an array of array, then i copy this array in another one, do an unset and display both: $a["row1"]=array("row1.1"=>"row1.1.1" , "row1.2"=>"row1.2.1"); $a["row2"] = array("row2.1"=>"row2.1.1", "row2.2"=>"row2.2.1"); print_r($a); $temp=$a; unset ($temp["row2"]["row2.1"]); print_r($temp); print_r($a); it works as expected, the unset within $temp does not affect rows within $a. BUT, if you replace $a=>$_SESSION, the unset within $temp do the same thing within $_SESSION!! The row is unset within $temp AND $_SESSION!! How do you explain that?
How To Reference An Array In Multidimensional Array?
How do I reference an array within an array? $mapped_array = array_map(null, $data_array, $counter_array); // okay, so now I have an array of 2 arrays - but how do I reference each array? // the next two lines fail to give an accurate count echo "Starting with ".count($mapped_array[0])." elements in data_array<br>"; echo "Starting with ".count($mapped_array[1])." elements in counter_array<br><br>"; // now I want to start at the bottom and look for an IP in each line of data_array // which I assume is mapped_array[0] for ( $i=count($mapped_array[0]); $i > 0; $i-- ) { $data_line = $mapped_array[0][$i]; $data = explode("|", $data_line); if( in_array($ip, $data) ) { // if there's a match, element[$i] of both arrays needs to be spliced out array_splice($mapped_array,$i,1); } } // again, these next two lines fail to return an accurate count echo "Ending with ".count($mapped_array[0])." elements in data_array<br>"; echo "Ending with ".count($mapped_array[1])." elements in counter_array<br><br>"; Is there something about array_map that prevents me from referencing the arrays within the array?
Remove Array Elements With The Given Value From Array
If I have an array, $myarray, with the elements values like (1, 2, 3, 6, 8, 10). I need a function applies to this $myarray to get rid of the element with certain value such as array_function_i_am_looking_for($myarray, 3) will return $myarray with the values (1, 2, 6, 8, 10). I checked out the array function manual. The closest one is array_filter. And I just need to write a function to compare the value for array_filter.
"Array To String Conversion" Error When Constructing A Multi-dimensional Array
I'm a bit stumped as I am getting a "Notice: Array to String Conversion" error when trying to do something that on the surface should be a very simple task - create an array, and write a set of values to them based on data submitted from POST Fields. Code below: $_SESSION["increment"] = array(); $x = 0 // Counter - This will be incremented $_SESSION["increment"][$x] = array("increment_bond" => $_POST["increment_bond"], "increment_amount" = $_POST["increment_amount"], "increment_comm_date1" = $_POST["increment_comm_date1"], "increment_comm_date2" =$_POST["increment_comm_date2"], "increment_comm_date3" = $_POST["increment_comm_date3"]); It keeps throwing out that error, and does not write any of the POST Values to the array (the POST values are definitely getting sent, so that is not the problem). If I dump out the value of $_SESSION["increment"], I get "1A" ?!? I'm sure that there is a pretty simple mistake lurking somewhere - I just can't seem to figure it out.
Putting An Array Within An Array?
Still having fun trying to build the perfect form and validation classes and wondered if anyone can help on the following. In the following function, how can I make $validationparameters an array so it can accept multiple values that I can iterate through? Don't need the iteration part (yet). function setField($type, $name, $value, $style, $label, $validationparameter) { $this->number_of_fields++; $this->fields[] = array('type'=>$type, 'name'=>$name, 'value'=>$value, 'style'=>$style, 'label'=>$label, 'validationparameters'=>$validationparameters); } This is part written function that I will use to pass the multiple values to the array. function setValidationParameters($number, $parameter) { $this->fields[$number][validationparameter] = $parameter; } I am beginning to confuse myself and wondering if anyone can add some sanity to what I am doing.
Combine Array Of Array
$array1 = array( array( "product_id" =3, "SKU" ="AES46", "qty" =3, ), ); $array2 = array( array( "product_id" =3, "SKU" ="AES46", "qty" =2, ), array( "product_id" =4, "SKU" ="AES47", "qty" =3, ), ); I want to add up the qty of two array if the product_id is same I try on $array1 + $array2, but which is not I want, I only have to use 2 foreach loop in my mind foreach ($array1 ...) foreach ($array2 ...) if ( id same ) Have other better suggestion or PHP function for this ? I am using PHP 4.4
Getting An Array Out Of A Superglobal Array
I have an array called $trackarray[] each index contains a number and i need to loop through this array and access each member to get the number. for example Code: $no_of_tracks = $_POST[$trackarray[$y]]; echo $no_of_tracks; for ($x=1; $x<=no_of_tracks; $x++){ .... do stuff....} $y above is the index number of the track array i need to access so would be 0, 1, 2 etc but because its been put in the POST array i dont know the syntax to get it back out I either get an error about " and ' marks or it returns nothing. Any ideas?
Array Inside Array
I have got an array. In this array, there are multiple arrays. I want to show some of the info in one of the arrays which are inside the main-array. It's like this: $array = Array( [test] => Test, [lala] => Array(with content in it)....); I thought I just could say "print $array[lala][0];", and it would give me the first value of "lala" in the $array. This does not work, so how can I do it then?
JS Array - Using PHP To Populate JS Array
I have a page where two select boxes containing lists of people ( Left is Absent and Right is Present) driven by several arrays, such as absent_Member, absent_Visitor, and present_Member, present_Visitor. This is so that an additional select box can be used to choose which category you want the select box to display. You can click on people on either side and click a button to swap them across. That is the easy part. The part I am stumped on is my familiarity with JS arrays. I am used to the ease of PHP for searching for values within arrays, such as in_array(needle, haystack); When I swap from on box to another, the only values being passed are options.value ( this equals the persons database ID # ) and options.text ( this equals the persons Last, First name ). The best way I can think to search the arrays to find which one this person resides in is a pathetically taxing way, such as Code:
Sorting An Array With Another Array
I have an array that is an order of things: array(23,54,1,45,12,9) And then I have an array of values from the table. Within this array is an id which relates to the previous array. It holds quite alot of information so I'm hoping there might be an easy way, as opposed to the long and messy way, to sort this array with the values in the other array. Looking through the array functions, I can't quite see it. Any advice on this one?
No Array Entry Vs Null Array Entry
Consider this statement related to Fields sent to PHP via an HTTP POST. $A = $_POST["FieldName"]; If the page did not have a form field with FiledName, the result is that $A is empty. If the page DID have a form field with FieldName, but the field was left empty, then $A is empty also. How should I test $_POST to distinguish between these two conditions.
2D Array
What i want is something like for ($i=0;$i<$var;$i++) { create 2D array if (condition) { push element in array // } } ie..1=>a,b,c,d 2=>e,f,g etc then i want to count the size of each array element eg. for array1 : no of elements 4 for array2 : no of elements 3 etc Not done 2D arrays before.
Array Help
Is it possible to do what I want to do with the $no_read_extentions array? instead of repeating the code with each extention in preg_match.
Array Of An Array
I have a problem. I have a text file that looks like this: usernameassword otherusernametherpassword I broke up each line into an array using explode, so now my array[0] is "usernameassword and array[1] is "otherusernametherpassword". I want to break up each array into 2 separate arrays. For example: farray[0] = "username" farray[1] = "password" sarray[0] = "otherusername" sarray[1] = "otherpassword" How can I do that?
Db Or Array
I don't know if I should store details like meat eater, veggie etc etc in a db and call it into a drop down menu or create a function with an array of different options i.e. #1 can relate to "meat eater" #2 can be "veggie" Thing is I'm trying to make as less possible connections to the db as possible as it slows down the server.
Array() 1D Or 2D
I have a form sending through $prod_id and $qty. I want to store $prod_id and $qty in $_SESSION["products"]. at the moment I want to store $prod_id as key and $qty as value in the session. I need to be able to add more $prod_id's and $qty's to the session but running into problems. The new $prod_id's and $qty's should not duplicate in the sesson, if a dupliicate is found for that $prod_id it must over write that $prod_id and $qty, and if no duplicate is found it must just add.
Array
Im tring to create like a telnet script but i dont know how to intergrade the arrays correctly in my script... when i few my script i get c: array in my telnet window... see i have added commands in the array. PHP Code:
|