PHP - How To Sort Multidimensional Array?
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.
Similar TutorialsHi freaks, Got a simple one for ya, I THINK? I have a multi-array that resembles this.. Code: [Select] $_SESSION["book_array"] = array(0 => array("plantID" => $plantID, "botanicalName" => $botanicalName, "commonName" => $commonName, "use" => $use)); I would like to sort it by the botanicalName key of the inner array before I call the forech loop that renders the display so that after it renders the table the items will be seen alphabetically, code below.. Code: [Select] <?php $bookOutput = ""; //$plant_use_array = ''; if (!isset($_SESSION["book_array"]) || count($_SESSION["book_array"]) < 1) { $bookOutput = '<tr><td colspan="4"><h6>Your Book is EMPTY!</h6></td></tr>'; } else { // Start the For Each loop $i = 0; foreach ($_SESSION["book_array"] as $each_item) { $plantID = $each_item['plantID']; $botanicalName = $each_item['botanicalName']; $botanicalName = stripslashes($botanicalName); $commonName = $each_item['commonName']; $commonName = stripslashes($commonName); $use = $each_item['use']; //$x = $i + 1; // Dynamic table row assembly $bookOutput .= "<tr>"; $bookOutput .= '<td><a href="plant_details.php?plantID=' . $plantID . '" id="bodyLink">' . $botanicalName . '</a></td>'; $bookOutput .= '<td>' . $commonName . '</td>'; $bookOutput .= '<td><strong>' . $use . '</strong></td>'; $bookOutput .= '<td><form action="book.php" method="post"><input name="removeBtn" type="submit" value="Remove"/><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>'; $bookOutput .= '</tr>'; $i++; } } ?> Any help would be much appreciated! Thanks in advance. I have a multidimensional array that I want to sort by "price" then by "date". Here is an example of the array: Code: [Select] $productArray = array ( array ("Bus", "1/1/2010", 15.99), array ("Train", "2/1/2010", 14.99), array ("Car", "3/1/2010", 18.00), array ("Plane", "3/1/2010", 15.99), array ("Bike", "3/1/2010", 9.99), array ("Truck", "1/1/2010", 19.99) ); //sort by date function sortElement1Asc($x, $y) { if ( $x[1] == $y[1] ) return 0; else if ( $x[1] < $y[1] ) return -1; else return 1; } //sort by price function sortElement2Asc($x, $y) { if ( strtotime($x[2]) == strtotime($y[2]) ) return 0; else if ( strtotime($x[2]) < strtotime($y[2]) ) return -1; else return 1; } usort($productArray, 'sortElement1Asc'); usort($productArray, 'sortElement2Asc'); Unfortunately this is just sorting by price (or whatever i sort last). Any ideas? We are toying with the idea of using PHP to do sorting instead of our database to reduce load and scale. Basically what we would have is multidimensional arrays that are resturned from the SQL engine and we will need to sort them on a specific key in PHP. We have written this functionality, but are looking to make it faster ANYWAY possible. Do you guys see anyway to speed up this code, without throwing more hardware at the problem yet? Currently on our test server this code takes approx 2.4 - 2.6 seconds to execute. We would love others to try this code and report what it takes them to execute. We are shooting for sub 1 second time. Code: [Select] $array = array(); $temp = array(); for($i = 0; $i < 100000; $i++) { $temp['id'] = rand(10000, 99999); $temp['history_id'] = rand(100000000, 999999999); $array[] = $temp; } //// // Start timer //// $mtime = microtime(); $mtime = explode(" ",$mtime); $mtime = $mtime[1] + $mtime[0]; $starttime = $mtime; //// // Actual sort //// usort($array, function($a, $b) { //Compare numbers if ($a['history_id'] == $b['history_id']) { return 0; } return ($a['history_id'] < $b['history_id']) ? -1 : 1; }); //// // End timer //// $mtime = microtime(); $mtime = explode(" ",$mtime); $mtime = $mtime[1] + $mtime[0]; $endtime = $mtime; $totaltime = ($endtime - $starttime); //// // Output execution time //// echo "Executed in: <strong>". $totaltime ."</strong> seconds."; 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, 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 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 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'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 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 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: - I recently posted a simple query about ISSET and finally got that simple problem solved thanks to you guys. But I've hit a new snag. I've create a simple sort of cart, or record counter. While I can add/remove/clear items and display their affilated arrays, I don't know how to cycle through a multidimensional array that is dynamically set.
Something like $_SESSION['Primary'][$items][$attributes] - Where $items is a dynamic set, and $attributes is a fixed set of keys with values.
I can target individual $Items, or display all the items in there. But I can't display all the Items and their subsequent $attributes aswell. Do I have to write 1 set of Ajax code for just displaying the $items, and another for each individual set of $attributes? Or is their a way to cycle through each $item, and then all of it's(or specific) $attributes and values? I've tried using loops which logically work, but I can't pass it through json_encode.
Is there any documentation I could read in relation to this? I feel this is the key component to manuvering through a database of sorts. I'm just not entirely sure how to go about accessing multidimensional Array's without a ton of code that becomes redudent. And even then, it wouldnt work well with a dynamic setup.
Edited by 7blake, 07 November 2014 - 01:39 PM. 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. 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! <?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" } } } 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 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'm trying to create a multidimensional array of movies organized by genre. This should take the form of an associative array with genres as keys. Each of the arrays elements should be an array containing movie names. This is what I have: <?php $movies = array( array("SF" => "", "Terminator", "Soylent Green", "I Robot", "frankenstein"), array("horror" => "exorcist", "IT", "frankenstein"), array("comedy" => "holy grail", "blazing saddles", "young frankenstein") ); //echo $movies[0][0]."<br>"; //echo $movies[1][0]."<br>"; //echo $movies[2][0]; foreach ($movies as $c) { while (list($k, $v) = each ($c)) { echo "$k ... $v <br/>"; } } ?> this is the output: SF ... 0 ... Terminator 1 ... Soylent Green 2 ... I Robot 3 ... frankenstein horror ... exorcist 0 ... IT 1 ... frankenstein comedy ... holy grail 0 ... blazing saddles 1 ... young frankenstein you'll see Terminator is only listed as element 0 because there's an empty string in front of it. The first item in the array is liated as the value to the key while the second value is listed as element 0. It doesn't seem right to me. Hi guys, I'm working on a project and I can't wrap my head around on a calculation that needs to be done on a multidimensional array. Quick background, it's a hotel benchmarking tool and I need to calculate the market penetration index (MPI). I have an array with 3 main arrays. First 2 are the hotels which are being compared and the last one is the MPI array. Each array contains an array for every month the user selects. Inside THAT array is data that needs to be used for calculations. Here is an example: Code: [Select] Array ( [Competitive set] => Array ( [Sep 11] => Array ( [0] => Array ( [minmonth] => 2011-09-01 [maxmonth] => 2011-09-01 [nrcheck] => 13 [data] => 67.6 ) ) [Oct 11] => Array ( [0] => Array ( [minmonth] => 2011-10-01 [maxmonth] => 2011-10-01 [nrcheck] => 13 [data] => 63.6 ) ) [Nov 11] => Array ( [0] => Array ( [minmonth] => 2011-11-01 [maxmonth] => 2011-11-01 [nrcheck] => 13 [data] => 59.2 ) ) [Dec 11] => Array ( [0] => Array ( [minmonth] => 2011-12-01 [maxmonth] => 2011-12-01 [nrcheck] => 13 [data] => 54.6 ) ) ) [Test] => Array ( [Sep 11] => Array ( [0] => Array ( [minmonth] => 2011-09-01 [maxmonth] => 2011-09-01 [nrcheck] => 89 [data] => 71.5 ) ) [Oct 11] => Array ( [0] => Array ( [minmonth] => 2011-10-01 [maxmonth] => 2011-10-01 [nrcheck] => 89 [data] => 67.0 ) ) [Nov 11] => Array ( [0] => Array ( [minmonth] => 2011-11-01 [maxmonth] => 2011-11-01 [nrcheck] => 91 [data] => 63.1 ) ) [Dec 11] => Array ( [0] => Array ( [minmonth] => 2011-12-01 [maxmonth] => 2011-12-01 [nrcheck] => 89 [data] => 57.5 ) ) ) [MPI] => Array ( [Sep 11] => Array ( [0] => Array ( [minmonth] => 2011-09-01 [maxmonth] => 2011-09-01 [nrcheck] => 89 [data] => 71.5 ) ) [Oct 11] => Array ( [0] => Array ( [minmonth] => 2011-10-01 [maxmonth] => 2011-10-01 [nrcheck] => 89 [data] => 67.0 ) ) [Nov 11] => Array ( [0] => Array ( [minmonth] => 2011-11-01 [maxmonth] => 2011-11-01 [nrcheck] => 91 [data] => 63.1 ) ) [Dec 11] => Array ( [0] => Array ( [minmonth] => 2011-12-01 [maxmonth] => 2011-12-01 [nrcheck] => 89 [data] => 57.5 ) ) ) ) Currently the 'data' for MPI is wrong. That needs to become the data of the first array divided by the data of the second array and multiplied by 100 (percentage). How would I go about doing that? The foreach loops are a bit too big for me on this one. 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 a multidimensional array and i need sort it by two different key. I've tried almost every sort function but no chance. Code: [Select] Array ( [0] => Array ( [0] => 1 [id] => 1 [11] => this is test [main_txt] => this is test [12] => 943965420 [add_time] => 943965420 [13] => 1323356400 [add_date] => 1323356400 ) [1] => Array ( [0] => 3 [id] => 3 [11] => another test [main_txt] => another test [12] => 943965120 [add_time] => 943965120 [13] => 1323702000 [add_date] => 1323702000 ) [2] => Array ( [0] => 32 [id] => 32 [11] => oppss one more test [main_txt] => oppss one more test [12] => 943944900 [add_time] => 943944900 [13] => 1323702000 [add_date] => 1323702000 ) [3] => Array ( [0] => 5 [id] => 5 [11] => okay, this is last one. Seriously [main_txt] => okay, this is last one. Seriously [12] => 943937160 [add_time] => 943937160 [13] => 1323615600 [add_date] => 1323615600 ) ) I need sort by add_date(Newer to Older) first then add_time(Later to Earlier) later. I hope i made my self clear. |