Associative Array
I have a list of word/number pairs. I need to retrieve the word that has the highest number associated with it.
I have put this list into an associative array...
$array['apple'] = ཈'
$array['orange'] = Ɖ'
$array['pear'] = ཮'
...and ordered it using arsort() so that "pear" in this case is the first value, then hit a brick wall when I realised that echoing $array[0] didn't work on an associative array. Indeed, why would it? :)
Is there a simple way to retrieve the top value after it's sorted, or do you always need to know the name of the key to manipulate associative arrays?
Else, do I need to look into multidimensional arrays? Something like...
$array[0] = array('apple' => ཈');
$array[1] = array('orange' => Ɖ');
$array[2] = array('pear' => ཮');
At which point, I'm not clear on how this would be sorted based on the values of the nested arrays, and how you would then specify to retrieve the key of the nested array of the first key of the original array!
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Using The $value Of An Associative Array
I am using an associative array to populate one field of a form. I use the $key to obtain the numeric value I want to enter into one of my tables. I use the $value to display in nice text what the numeric key represents. I have no problem entering the $key into the table or displaying the $value on the form. My problem is in displaying the results of the processed form to the user: My form "action" is "processform". In processform I do the INSERT query and return a message to the user. It is in the message to the user where my problem comes in. I've only captured the $key from the form. How can I capture also the $value from the form post, so that when I display to the user what he or she has chosen on the form, the nice text will display rather than the (to them) meaningless id number? Code:
Associative Array
I have to search a db table, and count distinct records to get some results from a survey we've done. The record needs to be echoed along with the number of times it is recorded. Each field in the table has to be searched individually, so that we can see the answers for each question separately. I thought that I could do this with one query, maybe 'count distinct', but I couldn't get it to show both the value of the row, and the amount of times that value had been recorded. So, I have to do 2 queries, one getting the distinct values of the field, the other counting how many times they are recorded. Here's the 2 queries: Code:
Associative Array In Class
In PHP Version 4.3.6 I am trying get a value from a class member that is an associative array... class MyClass { $var row; function MyClass() { $this->$row = array("A"=>"Apple", "B"=>"Bob"); echo "One: " . $this->$row["A"] . "<br>"; echo "Two: " . $this->row["A"] . "<br>"; $cache = $this->$row; echo "Three: " . $cache ["A"] . "<br>"; } } But this is the output... One: Array Two: Three: Apple How can I get at the value of the associative array without making a local copy first!
Array_push() With An Associative Array?
Is there a way to add a key/value pair to an associative array? I'm tryint to do this, but it dosn't work. $author = array(); while ($row = mysql_fetch_array($result)){ array_push($author,$row[id],$row[name]);}
Associative Array Question - Newbie
I am in the process of designing (before coding) my first serious PHP/MySQL application and I have a question about the best way to store information. The application will allow users to view the voting record of different legislators. I have concluded that the most efficient way to store the data is in two tables: one that has details about each legislator (mp) and another that has the details of each piece of legislation (bill). Each legislators record will have a field that holds info in an associative array in the form (bill ID, vote result). This way, when a new piece of legislation is added to the database, one more value pair (bill ID, vote result) will be added to each legislators voting record field. My question is two part: Is this the most efficient way to store the data? and I suspect I will have to be using regular expressions to extract and format the data from the MySQL query. Are there some PHP or MySQL functions or syntax I would find useful in this process of retrieving the data? Any online tutorials? (mysql_fetch_array appears to create an array out of two fields - not really what I am looking for...) I realize this is a rather vague question, but if you have any suggestions, please let me know.
Make Associative Array Out Of String
I have a string that look something like this: $string = "weight, kg|1200|width, mm|220|prize|20000"; and I would like it to an associative array and print keys and value: weight, kg: 1200 width, mm: 220 prize: 20000 (The string above is fetched from a database) Anyone have any bright ideas how to do it?
Adding Values Onto An Associative Array...
I'm trying to develop a simple class which through the interface you can add elements to an array. The method I have used to add the elements is setContentFields($name, $field_type), I have used an array counter variable to increment the array index each time. To me this seems like a workaround, and I wondered if there was a more elegant way of doing this. The class is as follows:
Sorting An Associative Array Of Objects By Value?
I'm trying to sort an array of objects within an object. Included is a dumbed down example so that we can get at the meat of the issue without worrying about complexity or validation. Basically, Funk is an object that has a name (string) and a value(int). FunkThis represents an object containing a list of Funks, with each key corresponding to the name of the Funk. I want to sort this list by val, but I get a Warning: usort(): Invalid comparison function error when I run the script. Keep in mind that this is for PHP 4 I'm open to suggestions to getting this to work. <?php class Funk { var $name; var $val; function Funk($name,$val) { $this->name = $name; $this->val = $val; } function getVal() { return $this->val; } function getName() { return $this->name; } } class FunkThis { var $list; function FunkThis() { $this->list = null; } function add($funk) { $this->list[$funk->getName()] = $funk; } function compareFunks($a,$b) { $aVal = $a->getVal(); $bVal = $b->getVal(); if ($aVal == $bVal) return 0; if ($aVal $bVal) return 1; if ($aVal < $bVal) return -1; } function sortByFunk() { $list = $this->list; $this->list = uasort($list,"compareFunks"); } function show() { print_r($this->list); } } $a = new Funk("A",3); $b = new Funk("B",7); $c = new Funk("C",1); $d = new Funk("D",9); $e = new Funk("E",6); $funkthat = new FunkThis(); $funkthat->add($a); $funkthat->add($b); $funkthat->add($c); $funkthat->add($d); $funkthat->add($e); $funkthat->sortByFunk(); $funkthat->show(); ?>
[smarty] Addressing Associative Array
Given this assoc array: $dtl_array[0]['uom_array'][0][0]='key1' $dtl_array[0]['uom_array'][0][1]='value1' $dtl_array[0]['uom_array'][1][0]='key2' $dtl_array[0]['uom_array'][1][1]='value2' $dtl_array[1]['uom_array'][0][0]='key3' $dtl_array[1]['uom_array'][0][1]='value3' $dtl_array[1]['uom_array'][1][0]='key4' $dtl_array[1]['uom_array'][1][1]='value4' $sample->assign("dtl_array",$dtl_array); $sample->display(); How could I create a combobox out of $dtl_array in the templates? The following does not work: <select name="aname"> {section name=mm start=0 loop=$dtl_array.0.uom_array step=1} <option value="{$dtl_array.0.uom_array.mm.0}"> {$dtl_array.0.uom_array.mm.1} {/section} </select>
Values From Form Via Associative Array
I have a form which has a text field and a select box. There are many other fields also in the form . I need get the value of the text field or the select box, depending on which one has a value. Additionally it has to give the value only from the text field even if there is a selection made from the select box. I know that i can get post values from form like this: PHP Code:
How To Add An Element To The Middle Of An Associative Array ?
I got an array that consists of elements that are arrays also. Now I wish I could add an element to the middle of it. Let mi give you an example: array ( - array(1,15,apple), - array(2,28,banana), - array(3,41,orange) } I would like to add, let's say, carrot on 2nd position: array ( - array(1,15,apple), - array(2,57,carrot), - array(3,28,banana), - array(4,41,orange) } Array_splice() does not work (or maybe i use it in a wrong way? - it splits an adding element for, in that case, 3 elements). Array_push() adds only to the end of an array. can samobody tell me how to add and element to the middle of an associative array?
Sort An Associative Array Alphabetically
I am working on a product catalog where it displays a product type on a page via the type variable. The products should be displayed alphabetically by $make and $model and i couldn't find any snippets or info other than asort etc. Just curious if anyone else needed such a sort function and how they did it. ie: product makes Maico, Madsen, Bio-logic etc and their models MA-300, Itera, AC-200. So I would have listings like Maico MA-300, Maico MA-800, Madsen Itera etc., and I need these alphabetical using make and model values. PHP Code:
How To Print A Multidimensional Associative Array?
I have the following associative array: $user["john"]["mozilla"]=1; $user["john"]["xmms"]=1; $user["doe"]["mozilla"]=0; $user["doe"]["office"]=1; $user["paul"]["mozilla"]=0; $user["paul"]["xmms"]=1; $user["paul"]["office"]=1; How can I print such an associative array using a loop statement like foreach?
Setting Values In Associative Array To 0
Ive tried almost every combination of while,foreach, key, value , array,0 I can some up with Ive got an associative array that Ive been using as a counter eg if (blah blah blah ) {$array['beans']++} elseif (something else){$array['peas']++} else {$array['carrots']++} I then want to reset all the values to zero foreach ($array as $key=>$value) { ??????? } or array_walk ?
XML Formatted String To Associative Array
I'm working on a php socket server for my chat room, and I need to parse some very short XML messages like this: <msg t="usr"><body a="pubMsg" u="username"><![CDATA[some message]]></body></msg> Right now I'm using a bunch of substrings (start laughing. lol), but it's very inflexible. However somehow it works... The problem arises when I try to store user variables (ignore the indents and line brakes, in reality, there will be non of them; we don't want to waste bandwidth) <msg t="usr"> <body a="updVar" u="username"> <var t="s" n="varname"><![CDATA[some variable]]></var> <var t="n" n="someNum"><![CDATA[3]]></var> </body> </msg> I have no idea how to parse those stuff from a string to an associative array... What I want is an associative array that I can access those stuff similar to this way: echo myXML['firstChild']['firstChild']['firstChild']['attributes']['t']; and it should output "s"
PHP Stops Processing On Multidimensional Associative Array
When using a multidimensional associative array to cross-reference data in a second, single-dimensional array, PHP stops processing data after a few iterations. Memory usage according to the task manager doesn't seem to spike and CPU usage only gets as high as 11 to 13 percent. A sample script is provided below, any help or alternative solutions are welcome. (By the way, the script below works fine on Linux with the same version of Apache and PHP. Possibly a PHP configuration issue?)
Printing Out An Associative Array - Whats Wrong?
I have this code segment: $query = "Select * from Payments order by CustID"; .. .. /* execute the query */ .. if (ora_exec($cursor)) { $recordset=array(); while (ora_fetch_into($cursor,$recordset,ORA_FETCHINTO_N ULLS| ORA_FETCHINTO_ASSOC)) { echo $recordset["CustID"]."<BR>"; echo $recordset["Amount"]."<BR>"; } } Gives me the following error Notice: Undefined index: CustID Notice: Undefined index: Amount The table Payments has only CustID and Amount as attributes. is my usage of the array offset incorrect?
Complex Associative Array To XML FIle And Back
We're using php 4.1 and it doesn't seem to have built in support for this. Coming from a dotnet background this surprised me...Anyways, thats a different topic altogether... I'm looking for a php class that can allow me to save a complex associative array as an xml file on our server and also be able to read in back into a complex array when needed. (you'll find an example of the array below). Because of the complexity if the array, I feel it would be easier to use this method as opposed to saving to a db. I know i could write a class to do it, but I'm trying not to reinvent the wheel. Googleing only refers me to extentions like pear which I dont want. And I 'm sure someone else has had to do this before. //ARRAY EXAMPLE ...
POST (or GET) Associative Array To Script From Form
Actually thought I understood this but I can't seem to make it happen this morning, and I can't seem to find a clear simple reference here. Can I pass an associative array from a form (using either POST or GET) to a .php script all at once, in one simple step? ie. Say I have the following variable/associative array $graphtable = Array ( [TESTPHASE] => G085 [GRADE] => 3 [0_LE_1_A] => 0 [1_LE_1_A] => 7 [2_LE_1_A] => 28 [3_LE_1_A] => 22 [4_LE_1_A] => 7 [null_LE_1_A] => 0 [PROTOCOLS] => 64 ) And I pass it as a hidden variable in the following form: ....
Associative Arrays
Basically I am writing a shopping cart from scratch. I can get my first item looking good but I can never add to my cart. If I choose another item it seems to overwrite the first one. Code:
PHP ADODB DB2 Associative Arrays
I know this doesn't -exactly- match php, but its still related, and adodb doesn't have its own google group yet, so i thought I'd go generic. The problem is, I created a nice little script for Oracle using oci8 and tried to convert to db2, but ran into issues. In case you don't know what ADODB is, checkout http://adodb.sourceforge.net/ The GetAssoc, or SetFetchMode(ADODB_FETCH_ASSOC) methods to get an associative array from a DB2 database don't function properly. The result of a simple query, for example: select firstname, lastname, dob from person results in an array something like: Array ( [LASTNAME] => 'Bob' [DOB] => 'Henry' [0] => ��-12-01' ) Now -that- is a real pain, and I've tried looking through the db2 driver, but couldn't pin-point myself where the problem was, as the ADODB code is a little out of my league, and the complications of the new 'extension' don't help. I was just wondering if anyone knows what I'm talking about? Or maybe a possible solution to the problem? I'd prefer a solution at the base level, not a 'quick-fix', as I use this library often. Some further information that might be useful is that i'm running DB2 v8.2 Enterprise, on WinXP (up-to-date). I'm using the latest ADODB 4.8.1 (NOT the extension). And i'm using Apache/2.2.2 + PHP/5.1.4 served on WinXP, same machine as DB2.
Associative Arrays Keys
I have a some text that i have to sort according to their year. The text is in this format.. A Short Story (2000) A long time ago (1999) A list (2004) Before Time (1999) Car parts (2004) so basically i want the output to be.. A long time ago (1999) Before Time (1999) A Short Story (2000) A list (2004) Car parts (2004) I thought the way to go about this would be to extract the years and put the whole thing in an associative array with the years as keys, but of course the keys have to be unique so in this case values override each other. PHP Code:
Sorting Associative Arrays...
I have an associative array which assigns arrays of 4 values to strings (see the example below): Array ( [value1] => Array ( [0] => 65 [1] => 2 [2] => 75 [3] => -10 ) [value2] => Array ( [0] => 65 [1] => 2 [2] => 0 [3] => 65 ) [value3] => Array ( [0] => 15 [1] => 2 [2] => 5 [3] => 10 ) ) Up to now, I've been using ksort on the big array and it sorted it by the "value1", "value2", etc., alphabetically. Now, however, I want it sorted numerically by the 4th value of each array inside the big array (the -10, 65, and 10 in the above example). How would I go about doing this?
Associative Arrays And Loops
I am trying to make database calls on what will potentially be a very large database. I would like to receive query results from the database using mysql_fetch_array() to get an associative array. Once I have this array, I want to show certain fields using my own formatting. If there are no fields, I want to show a "No Results" message. My code thusfar looks like this, and it does nothing if there is an invalid database query: Code:
Associative Arrays: Are Keys Strings?
I am wondering if it is 'wrong' (although it works) to work with associative arrays like this: $array[somekey] = blah instead of specifying the key as a string: $array["somekey"] = blah What would you say? What is right, what is wrong from the point of view of correct PHP coding?
Beginner With A Question About Associative Arrays
Is it possible to reference an index of an associative array using a variable? e.g.: If I had an array: $myArray["first"] = "myValue"; and if I were to declare a variable: $myVariable = "first"; I can't get PHP to display "myValue" by referencing this index using $myArray[$myVariable];
Interesting Insight Into Associative Arrays Versus Non-associatives...
We should all be familiar with the explode() and implode() functions. explode("Some String") --> "Some Array" implode("Some Array") --> "Some String" The idea is that each function goes back and forth between an array and string, provided you use a common delimiter. Now, let's look at a simple example, before I post my issue. 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:
|