PHP - Changing Values Of A Multidimensional Array?
Hi
I have an array which looks like this when i do a print_r(): Array ( => Array ( [path] => 1 [order] => 2 ) [1] => Array ( [path] => 2 [order] => 1 ) [2] => Array ( [path] => 3 [order] => 2 ) ) In this instance, I want to change the values of the order key. So I do something like this so that the last array has a path of 3 and an order of 1, and the others have orders of 2 foreach ($old_images as $old_image){ if($old_image['path']==3){ $old_image['order']="1"; } else{ $old_image['order']="2"; } } When i step through, i see that the order is changed, but when i do a print_r(), i get the same result. So even though im resetting the order value of the inside arrays, the multidimensional array does not change.... any ideas? Similar TutorialsHi all, I'm a first time poster here and I would really appreciate some guidance with my latest php challenge! I've spent the entire day googling and reading and to be honest I think I'm really over my head and need the assistance of someone experienced to advise the best way to go! I have a multi dimensional array that looks like (see below); the array is created by CodeIgniter's database library (the rows returned from a select query) but I think this is a generic PHP question as opposed to having anything to do with CI because it related to working with arrays. I'm wondering how I might go about searching the array below for the key problem_id and a value equal to a variable which I would provide. Then, when it finds an array with a the matching key and variable, it outputs the other values in that part of the array too. For example, using the sample data below. How would you recommend that I search the array for all the arrays that have the key problem_id and the value 3 and then have it output the value of the key problem_update_date and the value of the key problem_update_text. Then keep searching to find the next occurrence? Thanks in advance, as above, I've been searching really hard for the answer and believe i'm over my head! Output of print_r($updates); CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id] => Resource id #35 [result_array] => Array ( ) [result_object] => Array ( ) [current_row] => 0 [num_rows] => 5 [row_data] => ) Output of print_r($updates->result_array()); Array ( [0] => Array ( [problem_update_id] => 1 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Some details about a paricular issue [problem_update_active] => 1 ) [1] => Array ( [problem_update_id] => 4 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Another update about the problem with an ID of 3 [problem_update_active] => 1 ) [2] => Array ( [problem_update_id] => 5 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of four [problem_update_active] => 1 ) [3] => Array ( [problem_update_id] => 6 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of 6 [problem_update_active] => 1 ) [4] => Array ( [problem_update_id] => 7 [problem_id] => 3 [problem_update_date] => 2010-10-12 [problem_update_text] => Some new update about the problem with the ID of 3 [problem_update_active] => 1 ) ) I have the following multidimensional array; Array ( => Array ( [value] => Alarm [safe] => Alarm [view] => Alarm ) [1] => Array ( [value] => Deadlocks [safe] => Deadlocks [view] => Deadlocks ) [2] => Array ( [value] => Security Doors [safe] => Security Doors [view] => Security Doors ) ) I'm trying to implode the array to end up with an output like "Alarm, Deadlocks, Security Doors". But I cannot for the life of me work out the correct PHP. I'm assuming i need some foreach loop? Any help would be greatly appreciated. Hi I've set-up a multidimensional PHP array from a SQL query which pulls back parcels despatched per item on a daily basis. e.g. Item|Day1|Day2 |Day3|Day4|Day5 1 |100 | 120 | 90 |150 |60 2 |150 | 200 | 80 |90 |100 3 | 1 | 2 | 3 | 4 | 5 I want to be able to assign a ranked value to each day based upon the amount of items sent out each day and put that either into the existing array, or create a new array to which it can reference 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]); I am trying to get rows from MYSQL table (attachment) based on: Select last five rows where status_id = 1 Select last two rows where status_id = 2*I did use UNION with two SELECT queries to get whole data as one array. Now on PHP side... I have first block for rows having status_id 1 so if there are rows having status_id 1 then PHP should display the data otherwise if there is no row having status_id 1 then PHP should print NO DATA only once. I have second block for rows having status_id 2 so if there are rows having status_id 2 then PHP should display the data otherwise if there is no row having status_id 2 then PHP should print NO DATA only once. I did use foreach loop then within loop i did use if condition to check status_id of rows. it works fine when i omit NO DATA part but when i add it. the result shows both rows and NO DATA in first block when there are one or more rows having status_id 1 but no row having status_id 2 Which made me believe that i was doing it the wrong way. Please guide me *PS: I know its PHP section the thread should be related to PHP problem but... is it right to use UNION in query? or should i post a new thread in relevant section for guidance?
Hi all, I hope someone can help me out here as I think I am close but am not sure where to go from here. The problem is: I have a cms where a user can see a list of photos in the gallery. I provide them the ability to select what photos they want to appear on a particular webpage. The problem I have is that the user wants to be able to put the photos in whatever order they choose. So, I have a form (see attached), the html code is: <table width="566px" cellspacing="0" border="0"> <tr> <td width="33%"> <div class="serviceCell"> <input type='checkbox' checked='checked' name='photos[][0]' value='119' /> Bathroom Sin... <img src="./images/help.gif" title="Enter an integer to signify the order in which this image will appear on the webpage." alt="Enter an integer to signify the order in which this image will appear on the webpage."/> <input type="text" size="2" name="photos[][1]" value="0"/> </div> </td> <td width="33%"> <div class="serviceCell"> <input type='checkbox' checked='checked' name='photos[][0]' value='113' /> Courtyard 1 <img src="./images/help.gif" title="Enter an integer to signify the order in which this image will appear on the webpage." alt="Enter an integer to signify the order in which this image will appear on the webpage."/> <input type="text" size="2" name="photos[][1]" value="0"/> </div> </td> <td width="33%"> <div class="serviceCell"> <input type='checkbox' name='photos[][0]' value='114' /> Courtyard 2 <img src="./images/help.gif" title="Enter an integer to signify the order in which this image will appear on the webpage." alt="Enter an integer to signify the order in which this image will appear on the webpage."/> <input type="text" size="2" name="photos[][1]" value=""/> </div> </td> </tr>... Now, lets assume that the user ticked the box next to 'Courtyard 2' and entered an integer '1' in the input box to signify that this image should be displayed 1st on the chosen webpage. These 2 values go into the multidimensional array (photoid, ranking) and are submitted in the form to php in the photos[][] array. But here is where I have the problem. I am trying to extract the values from the array and then do an insert to a table in mysql. My syntax must be wrong somewhere so I am asking anyone to please offer any advice: if (isset($_REQUEST['submitted'])){ $photos = $_REQUEST['photos']; ... if(!empty($photos)){ foreach($photos as $photoID){ $sql = "INSERT IGNORE INTO menuItemPhotos SET photoid='$photoID[0]', menuItemid='$id', ranking='$photoID[1]'"; $ok = @mysql_query($sql); // execute the query } // End of foreach($photos as $photoID){ } // End of if(!empty($photos)){ Thanks Conor [attachment deleted by admin] Hi Just learning PHP and I'm struggling with a very simple problem. I'm playing around with arrays as i figure they're one of the most important things to know inside out but I can't work out how to change the value of an array element via a loop. I can obviously do it if I just directly write $cars[2] = "test" but not having any luck with the loop. I've tried using "foreach" and passing a new value to the $value variable but when i do a print_r the values in the array are unchanged. Code: [Select] $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; foreach ($cars as $key => $value) { $value = "TEST"; echo $key . " " . $value . "<br />"; } print_r($cars) I then tried using a for loop Code: [Select] for ($i=0; $i <= count($cars); $i++) { echo $cars[$i]; $cars[$i] = "2"; } But this code just threw up a fatal error as follows: "Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 16 bytes) in /home/zzzzzzzz/public_html/php_testing/arrays.php on line 27" So would someone be kind enough to explain where i'm going wrong and why i get the fatal error on the second for loop. Thanks Drongo Ok I am testing foreach in an array as my practice. I wonder how can I assign values in the key of the array.. Here's the code Code: [Select] <?php $username = me_mysql_prep(trim($_POST['username'])); $first_name = me_mysql_prep(trim($_POST['first_name'])); $last_name = me_mysql_prep($_POST['last_name']); $email = me_mysql_prep($_POST['email']); $position = me_mysql_prep($_POST['Position']); $password = me_mysql_prep($_POST['password']); $hashed_password = sha1($password); $required_fields = array($username,$first_name,$last_name, $email, $position, $password); foreach($required as $key => $value) { if($value == "") { echo $key . " Cannot be empty<br>"; } } ?> So the result would be like this... IF username, first name and last name are EMPTY it will echo: Quote username cannot be empty first name cannot be empty last name cannot be empty Anyone? 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? 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'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: - Hi 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. Trying to retun an array which gets a file from a directory and then returns the filename as the key and the complete file url as the value but when returning it it prints out "Array" for each file in the directory rather than the file name: Doing this in wordpress. Code: [Select] function wsme_select_css_theme(){ $alt_css_template_path = WSME_THEME_CSS; // Define path to files $alt_widgets_template = array(); // set array $out = ''; // Set var if ( is_dir($alt_css_template_path) ) { // If directory exists if ($alt_css_template_dir = opendir($alt_css_template_path) ) { //opens directory while ( ($alt_css_template_file = readdir($alt_css_template_dir)) !== false ) { //if files are in the directory if(stristr($alt_css_template_file, ".css") !== false) { //if the files are .css files $out[] = array($alt_css_template_file => WSME_THEME_CSS.'/'.$alt_css_template_file); //create the array(filename => file path) for each file in the directory } } } return $out; // return array } } Code: [Select] array( 'name' => 'Style', 'id' => WS_THEME_PREFIX . '_style', 'headings' => array( array( 'name' => 'Theme CSS', 'options' => array( array('name' => 'Homepage', 'desc' => ' select the css file of the theme you want for your site', 'id' => WS_THEME_PREFIX . '_theme_css', 'value' => '', 'options' => wsme_select_css_theme(), 'type' => 'select' ) ) ) ) Any suggestions? I am having trouble searching for an item in a multi-dimensional array. Is there a way to search only one column in a multi-dimensional array? i.e: MULTI-DIMENSIONAL ARRAY ID Name DataTable 0 John Employee 1 Dan Employee 2 Matt Boss 3 Becky Supervisor Is there a way to only search the column "Name"(Column 2) using array_search() or similar? (i.e array_search("John",$ARRAY[Column2]) The help would be very much appreciated! Cheers, Dan 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 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. <?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" } } } |