PHP - Multidimensional Looping Fgetcsv
I have data in a flat file that looks like the following:
Code: [Select] ##### BEGIN PRODUCT LOOP ##### REF*19**OHIO VALLEY FLOORING PID*F*TRN***SUPERINTENDENT PID*F*MAC***CARINDR MEA**LN*125.0*FT MEA**WD*12.0*FT MEA**SW*0.500*FP CTP**PRICE1*9.790**SY****ST CTP**PRICE2*11.190**SY****CT ####### BEGIN INTERNAL LOOP ####### G43*003**INVENTORY SLN*1**O******SK*RKDA100AA591*****ST*A100A PID*F*COLOR***SAGE TWEED PID*F*35***A591 SLN*2**O******SK*RKDA100AA592*****ST*A100A PID*F*COLOR***CREAMY TOFFEE PID*F*35***A592 SLN*3**O******SK*RKDA100AA593*****ST*A100A PID*F*COLOR***GALAXY GRAY PID*F*35***A593 ######## END INTERNAL LOOP ######## LIN**GS*A161*MF*ROOKWOOD CARPET*ST*A161 DTM*007*20110413 ####### END PRODUCT LOOP ####### My problem is that the header information is on each line and not at the beginning of the file like most CSV formats. Like the following: Code: [Select] REF*19 (Would be a column in the database) --- I would need OHIO VALLEY FLOORING but for each Referenced SKU # PID*F*TRN (Would be a column in the database) --- I would need SUPERINTENDENT but for each Referenced SKU # PID*F*MAC (Would be a column in the database) --- I would need CARINDR but for each Referenced SKU # and so on... So the database output would look something like: [/code] SKU | PRICE1 | PRICE2 | COLOR ---------------------------|-------------------|---------------|------------------ RKDA100AA591 | 9.790 | 11.190 | SAGE TWEED RKDA100AA592 | 9.790 | 11.190 | CREAMY TOFFEE RKDA100AA593 | 9.790 | 11.190 | GALAXY GRAY [/code] How would I define each row in the data set and get the information for each row to stuff in the database? Thanks for any help you can provide. This is what I have at present: Code: [Select] print_r(buildStock('832x12Data.txt')); function buildStock($File) { $handle = fopen($File, "r"); $fields = fgetcsv($handle, 1000, ","); while($data = fgetcsv($handle, 1000, ",")) { $detail[] = $data; } $x = 0; $y = 0; foreach($detail as $i) { foreach($fields as $z) { $stock[$x][$z] = $i[$y]; $y++; } $y = 0; $x++; } return $stock; } Similar Tutorials<?php $_SESSION["cart_item"] = array( 'cart_item' => array( 'id' => $id, 'product_name' => $product_name )); } $cart_items = $_SESSION["cart_item"]; foreach ($cart_items as $cart_item) { echo $cart_item["id"] . $cart_item["product_name"]; } ?>
I have tried several variations of the foreach loop like the one above and I mostly get the error message: Notice: Array to string conversion. When I use: I get the following output: array(1) { ["cart_item"]=> array(2) { ["id"]=> array(2) { [0]=> string(1) "2" [1]=> string(1) "3" } ["product_name"]=> array(2) { [0]=> string(19) "Adult Female Bike" [1]=> string(18) "Kids Unisex Bike" } } } I have a array as follows and I want to look by key where the key is 'ABCD', 'EFGH', etc.. I am using foreach but it is not working. How can I accomplish this? Code: [Select] Array ( [0] => Array ( [ABCD] => Array ( [venue_id] => 1003 [has_dining] => X [table_count] => 0 [serves_alcohol] => X ) ) [1] => Array ( [EFGH] => Array ( [venue_id] => 1003 [has_dining] => X [table_count] => 0 [serves_alcohol] => X ) ) ) I have an array which I contains multiple arrays, I would like to loop through and run a function on a certain key within the array I have the following code which works but I was wondering if there was a better method? $i = 0; foreach($Items as $Item) { $Items[$i]['key'] = custom_function($Item['key']); $i++; } The array $Items structure is as follows Code: [Select] array ( [0] => array ( [key] => 'blah' ) [1] => array ( [key] => 'blah' ) [2] => array ( [key] => 'blah' ) ) I'm pulling a list of topics from my DB and they are structured hierarchally using the typical id | parent_id scheme The array I end up with from the DB is one large one with keys representing the unique id of each data result...The problem is getting past the 2d scope of the array. I know this will require a recursive function and I've been at it for hours but can't seem to wrap my hurting head around it! How do I get my orignal array in this form: Array ( [0] => Array ( [1] => top parent [2] => top parent [3] => top parent [9] => top parent ) [2] => Array ( [4] => #1 child of 2 [5] => #2 child of 2 ) [3] => Array ( [6] => #1 child of 3 ) [4] => Array ( [7] => #1 child(subsub) of 4 [8] => #2 child(subsub) of 4 ) ) To look something more like this? : Array ( [1] => top parent [2] => Array ( [4] => Array ( [7] => #1 child(subsub) of 4 [8] => #2 child(subsub) of 4 ) [5] => #2 child of 2 ) [3] => Array ( [6] => #1 child of 3 ) [9] => top parent ) notice how the 2nd array has all the proper dimensions according the the DB hierarchy. Thank you ps. or maybe I should work from a different array to start from...I'm open to suggestions Hi I am uploading a csv file in the datbase. and i want to show an error message if the columns are more than 5. I am counting the rows in the below script but it always prints row 1. I have spent lot of time to figure out and google it. all the examples in google looks similar to mine. Can anyone find any issue with the below script and correct me pls Thanks in advance $row=1; $error = 'No'; //////////initialise the error flag while (($data = fgetcsv($handle, 1000, ",",'"')) !== FALSE) { if( count($data) > 5 ){ //print_r($data); $error = 'Yes' ; ///////////set the error flag to yes and break the loop . validation failed $errorMess = 'There are more than 5 columns in row # '.$row ; break ; } ///////////////insert the data into stagging table if the column ==5/////////////////// //print_r($data); $sqlLoad = "INSERT INTO ratecodes_stagging ( package_name,package_table,plan_name,plan_code,package_hierachy ) VALUES ('".addslashes($data[0])."','".addslashes($data[1])."','".addslashes($data[2])."','".addslashes($data[3])."', '".addslashes($data[4])."')"; $resultSqlLoad = es_query($sqlLoad); $row++; //echo $i."<br>"; }//END while fgetcsv I am trying to display rows starting with a specific tag when using fgetcsv() like rows starting with tag SY or AP where the first element of each such rows would have SY or AP has prefix example SY-Atlanta, SY-Texas, AP-Atlanta, AP-texas. The next columns in that row would have some data. I want to display only rows with above said prefix. What is the best way to do it? Use preg_match for each row and display it only if it has a match or is there any easier way? Sample data in csv: SY-Atlanta,0,0,0,5,9,9,0 SY-Texas,0,5,8,0,0,8.4 AP-Atlanta,9,4,8,9,0,0,0 AP-Texas,8,0,9,0,0,0,0 DF-Atlanta,8,4,9,3,0,0,0,0 DF-Texas,8,4,9,0,0,0,0,0 Hi I am trying to use this function to upload a CSV-format baseball schedule. I copied the example code from the manual website and it worked fine, printing out the contents, array style. I then added my code to the middle of this which just does a bit of analysis of dates and times for unix-style and then writes the stuff into a MySQL DB. It didn't work any more. As soon as I try to use fgetcsv it won't work. PLEASE HELP I have pulled all my remaining hair out! I checked my code with a magnifying glass but any hint of my code near fgetcsv stops the page loading. I am a web designer/PHP hack trying to solve a problem for our HR department. We have a quarterly newsletter in a Wordpress site I developed and they want to have a dynamically updated service anniversary page updated through excel. The solution to this problem is clearly fgetcsv, but I'm having trouble understanding how to implement it within the wordpress page. Here is a really nice function from the php manual page Code: [Select] <?php function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) { if (($handle = fopen("$source_file", "r")) !== FALSE) { $columns = fgetcsv($handle, $max_line_length, ","); foreach ($columns as &$column) { $column = str_replace(".","",$column); } $insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES"; while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) { while (count($data)<count($columns)) array_push($data, NULL); $query = "$insert_query_prefix (".join(",",quote_all_array($data)).");"; mysql_query($query); } fclose($handle); } } function quote_all_array($values) { foreach ($values as $key=>$value) if (is_array($value)) $values[$key] = quote_all_array($value); else $values[$key] = quote_all($value); return $values; } function quote_all($value) { if (is_null($value)) return "NULL"; $value = "'" . mysql_real_escape_string($value) . "'"; return $value; } ?> But this leaves me with a few questions: 1. is this both function AND query? or do i need extra code to run the function and spit out the results? 2. where do i input my actual values? 3. does this have to mirror a mysql table somewhere else? i feel like i'm missing a crucial piece of info here. the path to the csv file needs to be absolute, due to HR needing to manage the file themselves without the help of yours truly. the intended output will look like this: 5 YEARS FirstName1 LastName1, FirstName2 LastName2, FirstName3 LastName3, etc 6 YEARS FirstName1 LastName1, FirstName2 LastName2, FirstName3 LastName3, etc and so on. so in addition to the FirstName, LastName and Year columns, the loop will need to include a conditional statement. something like: Code: [Select] <h1>5 YEAR</h1> <ul> <?php if (quote_all_array(5) ) : ?> echo "<li>(FirstName, LastName), </li>"; <?php endif; ?> </ul> <h1>6 YEAR</h1> <ul> <?php if (quote_all_array(6) ) : ?> echo "<li>(FirstName, LastName), </li>"; <?php endif; ?> </ul> I'm sure my syntax is horribly wrong because I have virtually no idea what I'm doing. Which is why I'm asking you all for help to help my understanding i'll supply a set of variables: CSV Source: http://resource.mysite.com/anny.csv Table Columns: FirstName, LastName, Year External MySql database (should it apply): AnnySql Thanks in advance for any help. I'm over my pay grade on this one. Hey all, I've run into a bit of a problem when trying to use fgetcsv to dump the contents of a csv file into an array, in as much as fgetcsv stops after a line break. I've been using fputcsv to add content to the file and every time I use fputcsv it adds a line break, hense my problem. As you might have guessed from the time of this post (I'm in the uk) I've been trying to come up with a solution for this for quite a while; I'm pretty new to php as you might have gathered. Code: <?php $fname=data.csv $file=fopen($fname,"r"); $data=fgetcsv($file); echo "$data[0] $data[1] $data[2]"; ?> The csv looks something like this: adam,19 alex,16 andrew,24 etc... I'm able to access the first 2 values with $data[0] and $data[1], but when I try and access anything after the first line break, I get undefined ofset errors. If anyone could point me in the right direction to a solution for this problem I would be extremely greatful since I can't seem to find anything!! In the mean time, I'm off to catch up on some sleep. Cheers. Hello, I have a page where the user uploads a CSV file and I want to read that CSV and update database fields accordingly. It seems I have all the code correct but only the first row of the CSV is being imported. If I echo my variables within the loop, the only output is the first row of the CSV - no subsequent rows. I feel like I'm close but not sure what the issue is? Thanks a million for any help!! Jason //START FILE OPERATION $handle = fopen('uploads/testfile.csv', "r"); //LOOP CONTENTS OF CSV FILE while (($data = fgetcsv($handle, 1000, ",")) !== false) { $importID = $data[0]; $companyName = $data[1]; $primaryPhone = $data[2]; $primaryEmail = $data[3]; $billingFirstName = $data[4]; $billingLastName = $data[5]; $query = 'SELECT importID FROM import'; if (!$result = mysql_query($query)) { continue; } if ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { //UPDATE IF ENTRY EXISTS $query = "UPDATE import SET companyName='$companyName', primaryPhone='$primaryPhone', primaryEmail='$primaryEmail', billingFirstName='$billingFirstName' WHERE importID=$importID"; mysql_query($query); if (mysql_affected_rows() <= 0) { //NO RECORDS UPDATED } } else { //ENTRY DOESN'T EXIST } mysql_free_result($result); } //CLOSE FILE OPERATION fclose($handle);
Sometimes my 3 column .csv file has commas within quotes: When I use this code, I need the data count to stay the same "3" for each row: while (($data = fgetcsv($handle,2000,',')) !== FALSE) { print count($data); // prints "3" ... then prints "4" .... then prints "3" }
Thank you. Edited April 15, 2020 by StevenOliverI have ascript that loops through a directory of zip files, unzips to new directory and deletes the zip file and is supposed to import to mysql database. Everything works BUT writes empty records. Here is my code if anyone can help would be great Code: [Select] <?php include("sharons_dbinfo.inc.php"); $files = glob('gz/*.gz'); $texts = glob('*.txt'); foreach ($files as $in_file) { $file=str_replace(".gz","",$in_file); $file=str_replace("gz/","",$file); $file2=fopen($file,"w"); $gz = gzopen($in_file, 'r'); while (!gzeof($gz)) { $contents = gzread($gz, 10000); fwrite($file2, $contents); } gzclose($gz); unlink ($in_file); foreach ($texts as $text) { $handle = fopen("$text", "r"); while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) { $data = str_replace("'", "", $data); mysql_connect(localhost,$user,$password); mysql_select_db($database) or die( "Unable to select database"); $import="INSERT into new (`ID`,`PROGRAMNAME`,`PROGRAMURL`,`CATALOGNAME`,`LASTUPDATED`,`NAME`,`KEYWORDS`,`DESCRIPTION`,`SKU`,`MANUFACTURER`,`MANUFACTURERID`,`UPC`,`ISBN`,`CURRENCY`,`SALEPRICE`,`PRICE`,`RETAILPRICE`,`FROMPRICE`,`BUYURL`,`IMPRESSIONURL`,`IMAGEURL`,`ADVERTISERCATEGORY`,`THIRDPARTYID`,`THIRDPARTYCATEGORY`,`AUTHOR`,`ARTIST`,`TITLE`,`PUBLISHER`,`LABEL`,`FORMAT`,`SPECIAL`,`GIFT`,`PROMOTIONALTEXT`,`STARTDATE`,`ENDDATE`,`OFFLINE`,`ONLINE`,`INSTOCK`,`CONDITION`,`WARRANTY`,`STANDARDSHIPPINGCOST`) values('','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]','$data[14]','$data[15]','$data[16]','$data[17]','$data[18]','$data[19]','$data[20]','$data[21]','$data[22]','$data[23]','$data[24]','$data[25]','$data[26]','$data[27]','$data[28]','$data[29]','$data[30]','$data[31]','$data[32]','$data[33]','$data[34]','$data[35]','$data[36]','$data[37]','$data[38]','$data[39]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); } } ?>Thanks everyone
My .csv file has 3 columns and 10 rows $file = fopen('document.csv', 'r'); while (($data = fgetcsv($file)) !== FALSE) { $string .= $data[0].','.$data[1].','.$data[2]."\n"; } print $string; If I open the original .csv file in a text editor and replace all the invisible end-of-line "\r" with "\n" then the above code works fine. There must be an efficient way to implement this in my script, without having to remember to modify the original .csv file first.... Thank you in advance 😀 I need to extract data from a CSV file and insert it into a MySQL database. I am able to extract the data, however I cannot figure out how to group it. Sample File: 01 ISBN Name of Book Price 02 ISBN Name of Book Price So far I have an array with the entire file (reading file with PHP): Array ([0] => 01 [1] => 12345678X [2] => Title [3] => 120.00 ...etc. How can I modify the array to create groups of four for each item? Each item is its own array? Hi guys, I have a multidimensional array stored as a string in a database. How can I retrieve this information and make it act as a string? $query = mysql_query("SELECT string FROM database"); $result = mysql_fetch_array($query); $arr = array(); $arr[] = $result[string]; Would this have the required effect to make a string act as a multidimensional array? I've been working on some code to: 1. Search a db for rows that have a particular "position" value 2. Search the same db for rows that have a particular "langs" value 3. Compare the two arrays resulting for 1 and 2 4. Create a multidimensional array $langsarray[langs][question id] if 3 is true. 5. For each langs array in $langsarray pick a random, non-duplicate value and add it to $qarray for a maximum of 12 elements (3 for each langs). What I have works about 95%. The problem is, in the first langs array, one of the 3 randomly picked values is almost always empty, and its not always the same element. Sometimes its the first, sometimes its the third, sometimes its the second... I think I've narrowed down the issue to line 44 ($qtemp = ...). If I change the min/max values for the mt_rand function, it behaves slightly differently. Any help is much appreciated! Thanks in advance. Code: //Include MYSQL class and authentication information require_once('./include/mysql.php'); require_once('./include/global.php'); //Grab apptype from URL querystring $apptype = $_GET['apptype']; //Declare arrays $qarray = array(); $posarray = array(); $langs = array(); $langsarray = array(); //Get id's of all questions pertaining to position type $sql = 'SELECT * FROM qa WHERE position = "' . $apptype . '"'; $result = $db->query($sql) or die(mysql_error()); while ($row = $result->fetch()) { $posarray[] = $row['id']; } //Determine what types of questions should be pulled if ($apptype == 'fed'){ $langs = array('html','css','javascript','jquery'); } else if($apptype == 'bed'){ $langs = array('php','asp','javascript','jquery'); } //Get each question of each language that matches the position type and store it in the multidimensional array $langsarray[language][question id] $z = 0; while ($z < count($langs)){ $sql = 'SELECT * FROM qa WHERE langs = "' . $langs[$z] . '"'; $result = $db->query($sql) or die(mysql_error()); while ($row = $result->fetch()) { if (in_array($row['id'],$posarray)){ $langsarray[$langs[$z]][] = $row['id']; } } //Takes a random question id from the current language ($z) and adds it to the final question array. $y = 0; while ($y < 3) { //$qtemp = $langsarray[$langs[$z]][mt_rand(0,count($langsarray[$langs[$z]]))]; $qtemp = $langsarray[$langs[$z]][mt_rand(0,count($posarray))]; if (!in_array($qtemp,$qarray)){ $qarray[] = $qtemp; echo $qtemp . ', '; $y++; } } echo $langs[$z]; print_r( $langsarray[$langs[$z]]); echo '<br />'; $z++; } echo '<br />'; print_r($qarray); Output: 5, , 2, htmlArray ( => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) <--Problem 7, 6, 9, cssArray ( => 6 [1] => 7 [2] => 8 [3] => 9 [4] => 10 ) 14, 15, 13, javascriptArray ( => 11 [1] => 12 [2] => 13 [3] => 14 [4] => 15 ) 21, 17, 20, jqueryArray ( => 16 [1] => 17 [2] => 18 [3] => 19 [4] => 20 [5] => 21 ) Array ( => 5 [1] => [2] => 2 [3] => 7 [4] => 6 [5] => 9 [6] => 14 [7] => 15 [8] => 13 [9] => 21 [10] => 17 [11] => 20 ) <-- Final $qarray I am looking at the code below: Code: [Select] $array = array( array( 1, 2 ), 'a' => array( 'b' => 1, 'c' ) ); Is this an example of a multidimensional array? If so how would I access the value of 1 from key b? Also would the next line ('c') be automatically assigned to the asociative key of c? Ok, I have a couple multidimensional arrays that I am having problems with but it's all the same problem so I'll just use one. Basically it just takes input from a form and either creates or appends the array and then makes it a session variable. My problem seems to the the appending part. When I go to show the array (print_r() atm) it has only made the array with the newest record rather than adding the newest record to the existing set. Anyway here's the code. <?php session_start(); ?> $cushion = $_POST["Order_a_cushion_group_Cushion"]; $fabric = $_POST["Order_a_cushion_group_Fabric"]; $fill = $_POST["Order_a_cushion_group_Fill"]; $button = $_POST["Order_a_cushion_group_Button"]; $contWelt = $_POST["Order_a_cushion_group_Contrasting_Welt"]; $contWeltFab = $_POST["Order_a_cushion_group_Contrasting_Welt_Fabric"]; $zip = $_POST["Order_a_cushion_group_Zipper"]; $quantity = $_POST["Order_a_cushion_group_Quantity"]; if($contWelt == "N"){ $contWeltFab = "N/A"; } if($_POST["Default_submit"] == "Checkout"){ if(!isset($_SESSION["cushArray"])){ $cushArray = array(array(Cushion=> $cushion, Fabric=> $fabric, Fill=> $fill, Button=> $button, ContWelt=> $contWelt, ContWeltFabric=> $contWeltFab, Zipper=> $zip, Quantity=> $quantity) ); $_SESSION["cushArray"] = $cushArray; }else{ $sub = array(Cushion=> $cushion, Fabric=> $fabric, Fill=> $fill, Button=> $button, ContWelt=> $contWelt, ContWeltFabric=> $contWeltFab, Zipper=> $zip, Quantity=> $quantity )); $_SESSION["cushArray"] = $sub; } //header("Location:orderUserInfo.php"); print_r($_SESSION["cushArray"]); }elseif($_POST["Default_submit"] == "Add more"){ //echo "WTF"; if(!isset($_SESSION["cushArray"])){ $cushArray = array(array(Cushion=> $cushion, Fabric=> $fabric, Fill=> $fill, Button=> $button, ContWelt=> $contWelt, ContWeltFabric=> $contWeltFab, Zipper=> $zip, Quantity=> $quantity) ); $_SESSION["cushArray"] = $cushArray; }else{ $sub = array(Cushion=> $cushion, Fabric=> $fabric, Fill=> $fill, Button=> $button, ContWelt=> $contWelt, ContWeltFabric=> $contWeltFab, Zipper=> $zip, Quantity=> $quantity ); $_SESSION["cushArray"] = $sub; } //header("Location:orderPage.php"); print_r($_SESSION["cushArray"]); } ?> any help is greatly appreciated. Hello!
I am updating a current file which was using a simple array, I am updating it to use a multidimensional array.
<!DOCTYPE html> <head> <title>The Chinese Zodiac</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <?php function validateInput($year, $fieldname) { global $errorCount; if (empty($year)) { echo ("'$fieldname' is a required field.</p>\n"); ++$errorCount; $retval = ""; } else { // if the field on the form has been filled in if(is_numeric($year)) { if($year >=1900 && $year <=2014) { $retval = $year; } else { ++$errorCount; echo "<p>You must enter a year between 1900 and 2014.</p>\n"; } } else { ++$errorCount; echo "<p>The year must be a number.</p>\n"; } } //ends the else for empty return($retval); } //ends the function function displayForm() { ?> <h1 style="text-align:center">The Chinese Zodiac</h1> <br></br> <table border="1" width=100%> <tr> <form action = "<?php echo $_SERVER['SCRIPT_NAME']; ?>" method = "post"> <th><p>Year of Birth: <input type="text" name="year" /></p></th> </tr> <tr> <th><p><input type="reset" value="Clear Form" /> <input type="submit" name="submit" value="Show Me My Sign" /></p></th> </tr> </table> </form> <?php } function StatisticsForYear($year) { global $year_count; $counter_file = "counts/$year.txt"; if (file_exists($counter_file)) { $year_count = file_get_contents($counter_file); file_put_contents($counter_file, ++$year_count); } else { $year_count = 1; file_put_contents($counter_file, $year_count); } return ($year_count); }?> </head> <body> <?php $showForm = true; $errorCount = 0; $zodiac=""; $start_year=1900; if (isset($_POST['submit'])) $year = $_POST['year']; validateInput($year, "Birth Year"); StatisticsForYear($year); if ($errorCount==0) $showForm = false; else $showForm = true; if ($showForm == true) { //call the displayForm() function displayForm(); } else { //begins the else statement //determine the zodiac $zodiacArray = array( "Rat" => array( "Start Date" => 1900, "End Date" => 2020, "President" => "George Washington"), "Ox" => array( "Start Date" => 1901, "End Date" => 2021, "President" => "Barack Obama"), "Tiger" => array( "Start Date" => 1902, "End Date" => 2022, "President" => "Dwight Eisenhower"), "Rabbit" => array( "Start Date" => 1903, "End Date" => 2023, "President" => "John Adams"), "Dragon" => array( "Start Date" => 1904, "End Date" => 2024, "President" => "Abraham Lincoln"), "Snake" => array( "Start Date" => 1905, "End Date" => 2025, "President" => "John Kennedy"), "Horse" => array( "Start Date" => 1906, "End Date" => 2026, "President" => "Theodore Roosevelt"), "Goat" => array( "Start Date" => 1907, "End Date" => 2027, "President" => "James Madison"), "Monkey" => array( "Start Date" => 1908, "End Date" => 2028, "President" => "Harry Truman"), "Rooster" => array( "Start Date" => 1909, "End Date" => 2029, "President" => "Grover Cleveland"), "Dog"=> array( "Start Date" => 1910, "End Date" => 2030, "President" => "George Walker Bush"), "Pig"=> array( "Start Date" => 1911, "End Date" => 2031, "President" => "Ronald Reagan") ); switch (($_POST['year'] - $start_year) % 6) { case 0: $zodiac = $zodiacArray[0]; break; case 1: $zodiac = $zodiacArray[1]; break; case 2: $zodiac = $zodiacArray[2]; break; case 3: $zodiac = $zodiacArray[3]; break; case 4: $zodiac = $zodiacArray[4]; break; case 5: $zodiac = $zodiacArray[5]; break; case 6: $zodiac = $zodiacArray[6]; break; case 7: $zodiac = $zodiacArray[7]; break; case 8: $zodiac = $zodiacArray[8]; break; case 9: $zodiac = $zodiacArray[9]; break; case 10: $zodiac = $zodiacArray[10]; break; case 11: $zodiac = $zodiacArray[11]; break; default: echo "<p>The Zodiac for this year has not been determined.</p>\n"; break; } //ends the switch statement echo "<p>You were born under the sign of the " . $zodiac . ".</p>\n"; echo '<img src="Images/' . $zodiac . '.jpg">'; echo "<p>You share a zodiac sign with President " . $zodiacArray["$zodiac"]["President"] . ".</p>\n"; echo "<p>You are person " . $year_count . " to enter " . $year . "</p>\n"; } //ends the else statement ?> </body> </html>I need to be able to use the "switch command" (Assignment requirement), to get the animal name based on the code, but it is not working... Help is appreciated! I am having trouble displaying values in the multidimensional array at the bottom of this script. I can display the value of an element by specifying the sub-arrays e.g. echo $parsedxml['oaklistinfo']['contact']['contactname']; But surely there must be a way to specify an element without listing each of the sub-array names? Here's my code - Code: [Select] <?php //Copyright Daniel FAIVRE 2005 - www.geomaticien.com function simplexml2array($xml) { if (get_class($xml) == 'SimpleXMLElement') { $attributes = $xml->attributes(); foreach($attributes as $k=>$v) { if ($v) $a[$k] = (string) $v; } $x = $xml; $xml = get_object_vars($xml); } if (is_array($xml)) { if (count($xml) == 0) return (string) $x; // for CDATA foreach($xml as $key=>$value) { $r[$key] = simplexml2array($value); } if (isset($a)) $r['@'] = $a; // Attributes return $r; } return (string) $xml; } $issn = $_GET['issn']; $baseurl = "http://www.oaklist.qut.edu.au/api/basic?query=".$issn; $xml = simplexml_load_file($baseurl); $parsedxml = simplexml2array($xml); print_r($parsedxml); echo "<br />"; //$i = 0; //for ($i = 0; i<count($parsedxml[$i]); $i++) { echo $parsedxml['oaklistinfo']['contact']['contactname']; echo "<br />"; echo $parsedxml['record']['copyright']['copyrightstatement']; // } ?> |