PHP - Multidimensional Array Manipulation
Hi have an array() in which I would like to manipulate certain elements:
Code: [Select] Array ( [TESCO] => Array ( [Veg] => Array ( [Potatoe] => 12 [Cabbage] => 24 [Cucumber] => 56 ) [Meat] => Array ( [Chicken] => 54 [Beef] => 89 ) ) [ASDA] => Array ( [Veg] => Array ( [Potatoe] => 12 [Cabbage] => 24 [Cucumber] => 56 ) [Meat] => Array ( [Chicken] => 23 [Beef] => 90 ) ) ) How would I go about adding the price of my meat section together e.g. Chicken + Beef from ASDA = 113 Also how to add/remove elements from Meat/Veg? Like adding Pork Cheers Similar TutorialsHi pals, I got a complex Array from the Query. it's Structure is like Quote Array ( => Array ( [server_name] => anes.admod.net [id] => 1 [server_id] => 1 [description] => nice Anes Server [status] => 0 [max_down_count] => 9 [check_interval] => 15 [fail_recheck] => 6 [log_retain] => 1 [warning] => 12 [critical] => 15 [timeout] => 8 [audible] => Y [email] => Y [im] => Y [sms] => Y [rss] => N [rssid] => [vcare] => Y [created] => 2010-12-06 10:26:26 [last_update] => 2010-12-13 16:41:48 [name] => POP3 [port] => 110 [okay] => OK [warn] => WARNING [crit] => CRITICAL [down] => Connection refused [advanced] => N [typestatus] => 1 ) [1] => Array ( [server_name] => neseema.admod.net [id] => 2 [server_id] => 2 [description] => another server [status] => 1 [max_down_count] => 11 [check_interval] => 15 [fail_recheck] => 12 [log_retain] => 2 [warning] => 12 [critical] => 16 [timeout] => 6 [audible] => Y [email] => Y [im] => Y [sms] => N [rss] => N [rssid] => [vcare] => N [created] => 2010-12-07 10:27:42 [last_update] => 2010-12-13 16:41:48 [name] => Cpanel [port] => 2082 [okay] => OK [warn] => WARNING [crit] => CRITICAL [down] => Connection refused [advanced] => N [typestatus] => 1 ) [2] => Array ( [server_name] => anes.admod.net [id] => 3 [server_id] => 1 [description] => nice Anes Server another Service [status] => 1 [max_down_count] => 14 [check_interval] => 15 [fail_recheck] => 3 [log_retain] => 3 [warning] => 12 [critical] => 16 [timeout] => 18 [audible] => Y [email] => [im] => [sms] => [rss] => N [rssid] => [vcare] => N [created] => 2010-12-07 12:58:01 [last_update] => 2010-12-13 16:41:48 [name] => SMTP [port] => 25 [okay] => OK [warn] => WARNING [crit] => CRITICAL [down] => Connection refused [advanced] => N [typestatus] => 1 ) ) In this Result I have 2 Rows in result to show, I mean I need to merge the data of First (0th) and Third(2nd) element because it display the data of same item. So How it can done, I am working in that whole day but not get a solution fully.... I saw a near solution like : <?php $input = array( 0 => array ( 'id' => 160, 'payment_period' => 'Monthly', 'plan_payment_type_id' => 171, 'payment_type_id' => 4), 1 => Array ( 'id' => 160, 'payment_period' => 'Monthly', 'plan_payment_type_id' => 172, 'payment_type_id' => 5), 2 => Array ( 'id' => 161, 'payment_period' => 'Weekly', 'plan_payment_type_id' => 173, 'payment_type_id' => 9), ); echo "<pre>"; print_r($input); echo "</pre>"; echo "****************************************************************************"; $output = array(); $id_array = array(); $i = 0; foreach($input as $key=>$val) { if(array_key_exists($val['id'],$id_array)) { $pos = $id_array[$val['id']]; $output[$pos]['payment_types'][] = array('plan_payment_type_id'=> $val['plan_payment_type_id'],'payment_type_id' => $val['payment_type_id']); } else { $output[$i] = array('id' => $val['id'],'payment_period' => $val['payment_period'],'payment_types' => array(array('plan_payment_type_id'=> $val['plan_payment_type_id'],'payment_type_id' => $val['payment_type_id']))); $id_array[$val['id']] = $i; $i++; } } echo "<pre>"; print_r($output); echo "</pre>"; ?> But I cannot handle it nicely, please give any sample or helping code idea for same , waiting your immediate Reply Thankfully Anes P.A Hi, I'm trying to explode an array into a multidimensional array using <br /> tags as splitters but just can't get the syntax right! I can do lines of the array one by one, but not the whole lot at once. I'd really appreciate a quick example of an explode inside an array. $myarray looks something like this with print_r: ( [0] => [1] => some_html<br />some_html<br />some_html<br /> [2] => some_html<br />some_html<br />some_html<br /> [3] => some_html<br />some_html<br />some_html<br /> ) and I want to turn it into this: ( [0] => [1] => [0]some_html [1]some_html [2]some_html [2] => [0]some_html [1]some_html [2]some_html [3] => [0]some_html [1]some_html [2]some_html ) I've tried this $myarray = explode ("<br />", $myarray); but it doesn't work … It doesn't matter too much if there's are a few empty lines in the array from the final <br /> tags. Many thanks, as ever, for any help. I have the following array structu Code: [Select] [0] => Array ( [id] => Array ( [$t] => http://www.google.com/mate/ ) [updated] => Array ( [$t] => 2011-08-31T11:43:05.942Z ) [category] => Array ( [0] => Array ( [scheme] => http://schemas.google.com/g/ [term] => http://schemas.google.com/contact/ ) ) [title] => Array ( [type] => text [$t] => Name ) [link] => Array ( [0] => Array ( [rel] => http://schemas.google.com/contacts/2008/rel#edit-photo [type] => image/* [href] => https://www.google.com/mate/feeds/photos/media/ ) [1] => Array ( [rel] => self [type] => application/atom+xml [href] => https://www.google.com/mate/feeds/contacts ) [2] => Array ( [rel] => edit [type] => application/atom+xml [href] => https://www.google.com/mate/feeds/ ) ) [gd$email] => Array ( [0] => Array ( [rel] => http://schemas.google.com/g/2005#other [address] => email_address@gmail.com [primary] => true ) ) ) I am tried to display name and email address. I am using following method, can anyone tell me is there any better way? Thank u 4u help. NAME $name=( $emp_det[0]['title'][t]); $email =( $emp_det[0]['gdemail'][0][address]); Hi everybody, I generally find any assistance that I need on various sites, but this one has me stumped. I'm not overly advanced with my use of arrays, so I'd like some help here if anyone knows what I am looking for. I have a form that I would like to submit to a MySQL database. In that form, there is the ability to add up to 3 harddrives: Code: [Select] Brand: <input type="text" name="hdds[0][hddbrand]" id="hddbrand"><br/> Model and/or size,type: <input type="text" name="hdds[0][hddtype]" id="hddtype"><br/> SN: <input type="text" name="hdds[0][hddsn]" id="hddsn"><br/> Notes: <input type="text" name="hdds[0][hddnotes]" id="hddnotes" size="50"> Obviously the next harddrive would be hdds[1][hddbrand], etc. I am having an awful time looping through this to get more than 1 harddrive's information, however. I've tried foreach embedded in foreach and been messing around with this for a good 3-4 hours now and I feel like I am just missing something. I've got this right now to debug: Code: [Select] foreach($_POST['hdds'] as $key => $a) { $hddbrand = $a['hddbrand']; } my print_r($a) comes up with the following: Code: [Select] Array ( [hddbrand] => Toshiba [hddtype] => Shaba 500gb [hddsn] => 5fu8bvw4 [hddnotes] =>none ) 1 Good. That's what I want. But I need some help constructing my array/loop to get the values of more than 1 drive should I have to enter information for more than 1 drive. I feel like I am close, but I am just not getting what I need. I have not had to work with multidimensional arrays before and they are proving to be more trickier than I expected. Any help would be enormously appreciated! Patrick 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? 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? 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 trying to store all the elements of my tree in an array.My code produces multi dimensional array, but i want it to be one dimensional. How can i get it ? Code:- Code: [Select] function tree_gather($node) //Function to calculate count { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild']) || !empty($array['rchild'])) { $child[] = $array['lchild']; $child[] = $array['rchild']; $child[] = tree_gather($array['lchild']); $child[] = tree_gather($array['rchild']); } return $child; } Result:- Code: [Select] Array ( [0] => 2 [1] => 3 [2] => Array ( [0] => 4 [1] => 5 [2] => Array ( [0] => 10 [1] => 11 [2] => [3] => ) [3] => Array ( [0] => 8 [1] => 9 [2] => [3] => ) ) [3] => Array ( [0] => 7 [1] => 6 [2] => Array ( [0] => 15 [1] => 14 [2] => Array ( [0] => 16 [1] => 17 [2] => [3] => ) [3] => ) [3] => Array ( [0] => 13 [1] => 12 [2] => [3] => ) ) ) Table: - Hey guys, quick question. I have an array that looks like (blow). How can i sort it based on array[0][3], the #'s 1,2,3,4,5,6 are what i want to sort by in ASC order. Code: [Select] <?php Array ( [0] => Array ( [1] => Link Name [2] => URL [3] => 1 [4] => fy ) [1] => Array ( [1] => Link Name [2] => URL [3] => 2 [4] => fy ) [2] => Array ( [1] => Link Name [2] => URL [3] => 3 [4] => fy ) [3] => Array ( [1] => Link Name [2] => URL [3] => 4 [4] => fy ) [4] => Array ( [1] => Link Name [2] => URL [3] => 5 [4] => fy ) [5] => Array ( [1] => Link Name [2] => URL [3] => 6 [4] => fy ) ?> Thanks for the help. how to create multidimensional array in php I want to create an array based on data in a multidimensional array. Take, for example: $table[1] = array('husband' => array ('firstname'=> 'Albert', 'lastname' => 'Einstein', 'age' => 129), 'wife' => array ('firstname' => 'Mileva', 'lastname' => 'Einstein', 'age' => 128)); What would be the best approach, when you want to create an array with only the last names or the ages? Are there some things like wildcards in the PHP array universe to skip the first array level? Any suggestion is very appreciated. I tried several strategies, but ended up creating the same mulitdimensional array as above. Hi, I have an array of type array_name[roll_number][aggregate_marks]. How do I sort such array on 'aggregate_marks'? My attempts on sort, asort haven't worked. Hi All I'm new to php and I have a multidimensional array set up which I need to sort for a results list from an assessment. The array is $gradout['name']['userid']=score. I need to sort the array by score in a decending order. ['name'] is a string and ['userid'] is a numeric. I've tried looking at the php manual but It's just confusing me. Can anyone explain to me in laymans terms what I need to do and why. <?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" } } } Hi, I am trying to get a random monster from my multidimensional "monsters" array. I have array monsters, and inside that I have array "ocean" and inside that are "fish", "shark" etc. like the below, and I am trying to pick out a random monster from the Ocean array. Any help greatly appreciated. thank you. Derek here is the array Code: [Select] $monsters = array ( 'Ocean'=>array ( 'octalisk'=>array ( 'name'=>'octalisk', 'hp'=>100, 'damageLow'=>1, 'damageHigh'=>15, 'exp'=>10, 'ac'=>'HAVE TO LOOK THIS UP', 'monsterInitiativeModifier'=>'HAVE TO LOOK THIS UP'), 'shark', 'eel' ), 'Desert'=>array ( 'sand_snake' ), 'Forest'=>array ( 'frog', 'lizard', 'spider' ) ); I am trying to write a dirty script that removes duplicate rows from a multidimensional array. I want to be able to edit the function and spit the duplicates out to a CSV file. Here is my test file: $fullArray = array(array('Jim', 'Jones'), array('Pete', 'Pumpkin'), array('Barak', 'Obama'), array('Jason', 'Newstead'), array('Toby', 'Keith'), array('Jim', 'Jones'), array('Jim', 'Nelson')); echo "<h1>Original</h2>"; for($i=0; $i<count($fullArray); $i++) { echo $fullArray[$i][0] . " " . $fullArray[$i][1] . "<br />"; } echo "<h2>Checked</h2>"; $cleanArray = array(); $cay = array(); $nn=0; $dup=0; // Loop the entire input array foreach ($fullArray as $index => $item) { echo "foreach index:$index<br>"; // Start an internal pointer for ($f=0; $f<count($fullArray); $f++) { echo "for $f "; // if the index is lower or the same as the pointer, skip it to cut down on time if ($f > $index) { // if the rows are the same... if($fullArray[$f][0] == $item[0] && $fullArray[$f][1] == $item[1]) { echo "$item[0] DUP<br>"; // remove it from the array $cay = array_push($cleanArray, array($item[0], $item[1])); array_pop($fullArray[5]); $dup++; } else { // not a duplicate echo " not a dup<br>"; } } else { echo "ON THIS ONE<br>"; } } echo "<br><br>"; } echo"<br>$dup duplicates found<br><br>"; print_r($fullArray); echo "<br /><br>"; // print_r($item); print_r($cleanArray); ?> When I spit out the new fullArray variable, it still has an element from the duplicate record. This is what I get for the output of the full array after the duplicate was removed: Quote Array ( => Array ( => Jim [1] => Jones ) [1] => Array ( => Pete [1] => Pumpkin ) [2] => Array ( => Barak [1] => Obama ) [3] => Array ( => Jason [1] => Newstead ) [4] => Array ( => Toby [1] => Keith ) [5] => Array ( => Jim )[/b] [6] => Array ( => Jim [1] => Nelson ) ) Ok I have a multidimensional array and what I want to know is how to use it. I need to pick the items from the array but only the items specified or individual keys in the array how would I go about doing that. Here is the array: <?php $monstors = array ( "Skeleton"=>array ( "mob_name"=>"Skeleton", "mob_attack"=>"5", "mob_hp"=>"30", "mob_level"=>"1" ), "Skeleton Fighter"=>array ( "mob_name"=>"Skeleton Fighter", "mob_attack"=>"10", "mob_hp"=>"35", "mob_level"=>"2" ), "Skeleton Warrior"=>array ( "mob_name"=>"Skeleton Warrior", "mob_attack"=>"15", "mob_hp"=>"40", "mob_level"=>"3" ) ); ?> How would I like print_r the element in the array called Skeleton Warrior? I'm trying to pull out a list of id's into a simple array, but I seem to be getting is a multidimensional array. All I need is a simple array with the list of id's. What am I doing wrong? //Get list of all sentence id's selected for test in database $allSentenceQuery = mysql_query("SELECT id FROM associations WHERE validate='checked'") or die("First Query: ".mysql_error()); while ($allSentenceResult = mysql_fetch_array($allSentenceQuery)){ $allSentences[] = $allSentenceResult['id']; //echo "allSentences: ".$allSentenceResult['id']; } And what I get: "Array ( => Array ( [1] => 2 [2] => 3 etc...." Thanks for your help! Hi, Could really do with some help. So I've got a Multidimensional array like so Code: [Select] Array ( [Asia] => Array ( [0] => China [1] => Japan ) [Europe] => Array ( [0] => France [1] => Germany [2] => Spain [3] => UK ) ) I have a Mysql table (continents pre-filled) Code: [Select] Continent - Country Asia Europe I need to update country where continent is xxx So I need a query/php function which will when run would fill in "china, japan" into "asia" and "france, germany, spain, uk" into "europe", like so Code: [Select] Continent - Country Asia - China, Japan Europe - France, Germany, Spain, UK I don't really know where to start so I don't have a code. Would really appreciate some assistance. |