PHP - Multidimensional Arrays - Many Entrie With Same Datas..
I'm very beginner with arrays.... i KNOW, databases exist, it's more easy.. I can't use a database.. I have to use, this.. or similar.. that doesn't requiring a database engine... So... that array...
array ( ); I search by the element [#][0].. in the +250 some will contain the same infos and I would like to make them point to the element containing the info instead of repeating it and have to update at 3-4 places when it's time. Like what it's in "10" also good for "ten", "dix" and "diez"... anyway to make that simple? by reference or...??? I'm crying.. last time I used arrays... Turbo Pascal.. at school... or was it Turbo C++ 3.0?? Maybe it was with cobol... well it was the good ol' time of the 90s!
Thanks!
-TRP-
Similar TutorialsHello!
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! 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? 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. 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']; // } ?> Suppose I have a multidimensional array... $AnArray[1][$j] I'd like to count how many $j So if $AnArray = array(0 => array('orange', 'banana', 'apple'), 1 => array('carrot', 'collard', 'pea','tuna')); The count I'm after would be 4... How do i ouput it like this Code: [Select] Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) ) rather than this Code: [Select] Array ( [field_name] => first_name [field_type] => 1 [max_length] => 20 ) Array ( [field_name] => last_name [field_type] => 1 [max_length] => 40 ) Array ( [field_name] => email [field_type] => 1 [max_length] => 80 ) Code: [Select] $fields = array(); foreach ($_POST['use'] as $field){ $fields = array( "field_name"=>$field, "field_type"=>$match_types[$i], "max_length"=>$match_length[$i]); print_r($fields); echo $fields[0]['field_name']; //echo $field.' - Type: '.$match_types[$i].' - Lenght: '.$match_length[$i]."<br />"; $i++; } How do I find out how large a dimension of an array is? I have an array with an X and a Y coordinate, and in the 3rd dimension I store it as the value of an ID. so an array might be x,y,560; x,y,415, etc. I can run a counter within the loop to determine the total number of iterations of the loop, but that isn't an accurate picture of how large the 3rd dimension of the array is. Hi, I am building an online store, and have been using a tutorial to get me started. I have been adjusting the code as I require additional functionality and I have hit a brick wall... I have a multidimensional array that contains all of the information I have passed from the product page. What I want to do is write a piece of PHP code that will increase the quantity of a particular item based on 2 of 3 variables matching the data in the array. Below is the full working code which runs the adjustment based on... Code: [Select] <?php if ($key == "item_id" && $value == $item_to_adjust) { ?> What I want to do is add to the if statement like so... Code: [Select] <?php if (($key == "item_id" && $value == $item_to_adjust) && (($key == "custom_txt" && $value == $custom_txt) || ($key == "img" && $value == $fileName))) { ?> But this code doesn't seem to work, Is there another way to get the result I am after? Code: [Select] <?php // Section 3 (if user chooses to adjust item quantity) if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") { $item_to_adjust = $_POST['item_to_adjust']; $custom_txt = $_POST['custom_txt']; $fileName = $_POST['fileName']; $quantity = $_POST['quantity']; $quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers if ($quantity >= 100) { $quantity = 99; } if ($quantity < 1) { $quantity = 1; } if ($quantity == "") { $quantity = 1; } $i = 0; foreach ($_SESSION["cart_array"] as $each_item) { $i++; while (list($key, $value) = each($each_item)) { if ($key == "item_id" && $value == $item_to_adjust) { // That item is in cart already so let's adjust its quantity using array_splice() array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity))); } // close if condition } // close while loop } // close foreach loop } ?> Thanks in advance! Richi Hello there I'm new and quite stuck. So here we go! I have the following HTML form. Code: [Select] <form method="post" action="/Install/Step02/"> Server: <input type="text" name="MySQL[Server]" /><br /> Database: <input type="text" name="MySQL[Databaser]" /><br /> </form> Now to my understanding I should receive something along the lines of $_POST['MySQL']=>array();. But instead I get an empty string. Why is this? I have an array titled $uhits that looks like this: Array ( => Array ( [user] => test [hits] => 20 ) [3] => Array ( [user] => test3 [hits] => 6 ) [4] => Array ( [user] => test4 [hits] => 6 ) [1] => Array ( [user] => test1 [hits] => 4 ) [2] => Array ( [user] => test2 [hits] => 4 ) ) I've searched and tried so many different functions and am losing my mind after trying for 3 hours to be able to search for a specific user's value and then display it and the hits value. How in the world can I achieve this? I have a MySQL query that pulls multiple columns with many rows. I want to break each column into its own array. Here is what I have to this point but doesn't seem to be working. Is this the right direction or is there something easier? Thanks! Code: [Select] $query = "SELECT name, address, city, state FROM customers WHERE sku = '12345'"; $result = mysqli_query($dbc, $query) or die(); $name = array(); $address = array(); $city = array(); state = array(); while ($data = mysqli_fetch_assoc($result)) { $name = $data['name']; $address = $data['address']; $city = $data['city']; $state = $data['state']; } Hi wondering if there's a simple way to merge or update the data from one array to another . I've tried merge data but it just adds additional records rather than merging them off one common key.
The array is just simply adding a name to another array the format of both is as follows
Array 1
[0] => stdClass Object ( [name] => [market] => Football [selection] => 7051575 ) ) Array 2 Array ( [0] => stdClass Object ( [name] => Something [market] => [selection] => 7051575 ) ) There are other fields but I'm just trying to merge the name from Array two into Array one using the selection as a common key. Is there an easy command like merge or do I have to loop thru the arrays to add the data. Thanks Hi all I have an array and within that array that list categories. Each category has a sub category. I am trying to output in JSON and my problem is this: I am looping through each category and displaying the results. As the category has sub categories I am then looping through them and displaying the sub categories. This works fine, but my JSON is not valid because of a single comma: Code: [Select] { "config":{ "logo":"uploads\/global_config\/scaled_", "deliveryCost":19.99, "showPrice":"true" } }, "range":[ { "title":"Classic", "doors":[ { "id":19, "title":"Rembrandt" }, { "id":66, "title":"Picasso" }, { "title":"Heritage", "doors":[ { "id":29, "title":"Broadway" }, { "id":30, "title":"Draycott" }, { "title":"Regency", "doors":[ { "id":36, "title":"Canterbury" }, { "id":47, "title":"Exeter" }, <---- this comma is failing my json ], "product":{ "glass":[ { "id":7, "title":"Pad" }, { "id":6, "title":"Scroll" } ] } } My PHP: <?php echo '{'; $count = count($config) - 1; foreach($config as $key=>$conf) { $conf_price = $conf->getPrice() == '1'; if($conf_price) $conf_p = 'true'; else $conf_p = 'false'; echo "\"config\"".":",""; $config_array = array('logo'=>strtolower(str_replace(' ','-','uploads/global_config/scaled_'.$conf->getImage1())), 'deliveryCost'=>$conf->getDeliveryCost(), 'showPrice'=>$conf_p); if($key == $count){ echo json_encode($config_array).","."\n"; } else { echo json_encode($config_array).'},'."\n"; } } echo json_encode("range").": [\n"; $last_key = end(array_keys($categories)); foreach ($categories as $key => $cat) { if ($key == $last_key) { echo "{". "\"title\"".':'.'"'.$cat->getTitle().'"'.","."\"src\"".':'.'"'."-".strtolower(str_replace('.png','*.png',(str_replace(' ', '-', 'uploads/ranges/scaled_'.$cat->getImage1())))).'"' .","."\"info\"".':'.'"'.strip_tags($cat->getDescription()).'"'.","."\n"; } else { echo "{". "\"title\"".':'.'"'.$cat->getTitle().'"'.","."\"src\"".':'.'"'."-".strtolower(str_replace('.png','*.png',(str_replace(' ', '-', 'uploads/ranges/scaled_'.$cat->getImage1())))).'"' .","."\"info\"".':'.'"'.strip_tags($cat->getDescription()).'"'.","."\n"; } echo json_encode("doors").": [\n"; $count = count($cat->getAllDoorStyles()) - 1; foreach ($cat->getAllDoorStyles() as $key=>$door) { $array2 = array('id'=>$door->getId(), 'title'=>$door->getTitle(), 'src'=>strtolower(str_replace('.png','*.png',(str_replace(' ', '-', 'uploads/doors/scaled_'.$door->getImage1())))), 'price'=>$door->getPrice(), 'description'=>strip_tags($door->getDescription())); if($key == $count) { echo json_encode($array2).''."\n"."".","; } else { echo json_encode($array2).''."\n"."".""; } } } echo "\n"; echo "],"."\"Product:\"". '{ '; echo json_encode("glass").": [\n"; $count = count($glass) - 1; foreach($glass as $key => $glass_cat) { $glass_array = array('id'=>$glass_cat->getId(), 'title'=>$glass_cat->getTitle(), 'price'=>$glass_cat->getPrice(),'src'=>strtolower(str_replace('.png','*.png',(str_replace(' ', '-', 'uploads/glass_option/scaled_'.$glass_cat->getImage1()))))); if($key == $count) { echo json_encode($glass_array)."\n"; } else { echo json_encode($glass_array).','."\n"; } } echo ']'; echo '}'; echo '}'; I need to omit the comma that is causing me my problem All help welcomed Hi everyone, If you take a look at my code below I am having trouble echoing the key/ value pair of the 'sex' array which is a sub array of 'pens'. I have tried so many different ways but to no avail, thanks Chris! Code: [Select] <?php $products = array( 'paper' => array( 'copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", 'photo' => "Photographic Paper"), 'pens' => array( 'ball' => "Ball Point", 'hilite' => "Highlighters", 'marker' => "Markers", 'sex' => array ( 'condom' => "Protection")), 'misc' => array( 'tape' => "Sticky Tape", 'glue' => "Adhesives", 'clips' => "Paperclips") ); echo "<pre>"; foreach ($products as $section => $items ) foreach ($items as $key => $value) echo "$section:\t$key\t($value)<br>"; echo "</pre>"; ?> i am a newbie.. From my tables, what code should i put to put into my site? in text.. Dear All, I have login script already. i have two database one is users and another one is reference in both user_name is common. In this if a user login and search the refid means that user datas onle possible to retrieve. for others datas they cant access. i wrote the below code but it display all user datas. kindly help me <?php session_start(); if (!$_SESSION["user_name"]) { // User not logged in, redirect to login page Header("Location: login.php"); / } // Member only content // ... $con = mysql_connect('localhost','root',''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("login", $con); $user_name = $_POST['user_name']; $query = "select * from reference,users where reference.user_name=users.user_name and reference.refid='$refid'"; $result = mysql_query($query) or trigger_error('MySQL encountered a problem<br />Error: ' . mysql_error() . '<br />Query: ' . $query); while($row = mysql_fetch_array($result)) { echo $row['refid']; echo $row['origin']; echo $row['dest']; echo $row['date']; echo $row['exdate']; echo $row['user_name']; } echo "<p><a href=\"logout.php\">Click here to logout!</a></p>"; ?> <html> <form method="post" action="final.php"> Ref Id:<input type="text" name="refid"> <input type="submit" value="submit" name="submit"> </html> guys please help, i have an array(52,51,52) here i want to insert first & last elements into DB, not second one does not follows the series another array (52,52,53) in this case insert first 2 elements into DB since last element does not follow the series. how is this possible? Hello everybody, I have found a lot of amazing advises and codes to improve on my existing codes. It seems to be an awesome site. I actually came from a background of Application programming, however I have just recently pick up a project in php. The project is about database integration, where I have to integrate 5 supplier's existing data who have different attributes into one. (each suppliers have about 30k data) I really need help and advises on how should I do the script. Here's the details, All the suppliers uses different data file, such as CSV and .xls. I am finding a way to integrate all the 5 files into one database(mysql/phpmyadmin) so it could be listed out in a shopping cart or catalog in future. However, I am unfamiliar with php, so please advice on how can i go about fixing this problem. The first problem is that each individual suppliers uses a different attributes name, for example Supplier 1 uses : SupplierName, SupplierID, SupplierAddress, Status Inside the status, the supplier uses data such as, Good, Excellent, Great while Supplier 2 uses : SName, SID, SAddress, Status and inside this supplier, the status data that are being uses is G, Ex, Gr. How can I set a consistancy on the data and converting all the properties into one so I can import this data into a proper database such as mysql/phpmyadmin. Please help, thanks in advance I hav a php page which takes data from the db.But the problem i am facing is for a particular fild in database ,i have long data,which i need to b displayed in a wordwrap way eg my data is " Description need a site for school gave order on 12-10-2010 work started on 12-10-2010 " this shuld be displayed as "Description need a site for school gave order on 12-10-2010 work started on 12-10-2010" Description is the field in the database and rest of them are the datas in it guys, please help i have table with datas like speed of vehicle, position e.t.c from morning 8 a.m. to 8 p.m. I need to get these details, but after every 15 minutes i.e. after selecting datas at 8 a.m. it shd select datas @ 8.15 a.m. then 8.30 a.m. hw can i write a mysql query for this ? or a PHP approach is appreciated |