PHP - Php Loop Through Arrays Withing Arrays
I'm having troubling with trying to create a function to spit out a single array with the following array. I can write it in a away that looks through the arrays manually. the results i am trying to generate is that each item in generated array. Array to convert array( "account" => array( "login", "register", "logout", "edit", ), "p" => array( "report", ), "array1.0" => array( "array2.0" => array( "array3.0", "array3.1 ), "array2.1", ), generating the array will look like this
Array ( [0] => account [1] => account/login [2] => account/register [3] => account/logout [4] => account/edit [5] => p [6] => p/report [7] => array1.0 [8] => array1.0/array2.0 [9] => array1.0/array2.0/array3.0 [10] => array1.0/array2.0/array3.1 [11] => array1.0/array2.1 ) The idea is that id generates a single array with combined labels and arrays inside, etc. I just can't figure out how to create a script that will create this array even If I add a new value or array.
Similar TutorialsHow to use both Code: [Select] $matchInArray[$i] and Code: [Select] $matchInArrayR[$i] arrays work within the same loop? my code: $matchInArray = array($match1, $match2, $match3, $match4); $matchInArrayR = array($matchresult1, $matchresult2, $matchresult3, $matchresult4); if($getawayr='Group A'){ $numWins = 0; for($i=0; $i<9; $i++){ if($matchInArray[$i] == "W" && $numWins < 3){ $matchInArrayR[$i] = "Qualified for Semi Finals"; $numWins++; } } } I'm trying to create a series of functions, when activated: a. scans a target directory for jpg's -> returns file names to an array b. takes those file names and stripes the .jpg from them -> return file name, extension, and full filename c. inserts said file names into a MySQL database Here's the problem: The second function won't loop on the return array('name' => $name), it just does it once. Code: Function 1 (of 3) Code: [Select] function scanJpg($phpath){ $dir = opendir($phpath); while(false !== ($file = readdir($dir))){ if($file != "." && $file != ".."){ if(!is_dir($phpath.$file)){ $results[] = $file; } } } closedir($dir); return $results; } // returns // Array ( [0] => lakeonrefuge.jpg [1] => shasta04.jpg [2] => carly_lol.jpg [3] => beach_adventures_florence.jpg [4] => beach_adventures.jpg [5] => Beach-0168.jpg ) function 2 Code: [Select] function stripJpg($jpgs,$phpath){ foreach($jpgs as $jpg){ $ext = strrchr($jpg, '.'); if($ext !== false) { $name = substr($jpg, 0, -strlen($ext)); echo $name."<br />"; echo $jpg."<br />"; echo $ext."<br /><br />"; return array( 'name' => $name, 'filename' => $jpg, 'ext' => $ext ); } } } ## $jpgs = scanJpg($phpath); ## print_r(stripJpg($jpgs,$phpath)); ## ## returns the following ## Array ( [name] => lakeonrefuge [filename] => lakeonrefuge.jpg [ext] => .jpg ) What am I overlooking? Thanks in advance! 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 have two arrays as Code: [Select] $array1=array("word1","word2","word3"); $array2=array("term1","term2","term3"); How can I have a foreach loop to echo "word1-term1", "word2-term2", .... I mean having Code: [Select] echo "$array1[0]-$array2[0]";but in a foreach loop Let me explain my problem. I have an array with dates and numbers in format ($cronograma) Ex: Array ( [2020-09-21] => Array ( [0] => 2020-09-21 [1] => 2 [2] => 2 [3] => 2 ) [2020-09-28] => Array ( [0] => 2020-09-28 [1] => 2 [2] => 2 [3] => 4 ) Then i have another array with 2 ids (in this case 58,60) ($id) Finally i have a third array with numbers only (in this case 34,34) $tot So what i want is cross information beween them, for example for id 58 I must get dates (first element and last element when $tot = 34) for id 60 I must get dates (first element after $tot =34 and last element of array) Whath i have so far is this foreach ($id as $idPlan) { foreach ($cronograma as $c) { $t1 = 0; foreach ($tot as $d) { $t1 += (int)$d['tempos']; if ($c[3] == $t1) { $newAr[] =$idPlan; $newAr[] = $c[0]; } } } } My response array(8) { [0]=> string(2) "58" [1]=> string(10) "2021-02-01" [2]=> string(2) "58" [3]=> string(10) "2021-06-14" [4]=> string(2) "60" [5]=> string(10) "2021-02-01" [6]=> string(2) "60" [7]=> string(10) "2021-06-14" } null So it's clear that i have all repeated I should have a line like: 58 - 2020-09-21 -2021-02-01 Any help? Hi, This problem has been driving me crazy all day. I am relatively new to PHP. I basically am trying to populate a database with data from site users. I am using session variables to store their data temporarily as they navigate through the sign up process. A user will input how many 'categories' they wish to populate on page 1. Page 2 will then ask them to specify the details of each category. Eg Category 1: Title, Description, Amount. Category 2: Title, etc. So far I have been able to do this, I now want to store what they have input in session variables. My thoughts were to take the number of categories they have sepcified and create that number of arrays using a loop. Each array will store the details on each category. My code is as follows: Code: [Select] $count=$_POST['count']; //Get how many categories were added //Create an array for each category for ( $counter = 0; $counter <= $count; $counter++){ ${'Categoryarr'.$counter} = array(); }; for ( $counter = 0; $counter <= $count; $counter++){ $Categoryarr[$counter][1]=$_POST['amount_'.$count]; $Categoryarr[$counter][2]=$_POST['desc_'.$count]; $Categoryarr[$counter][3]=$_POST['title_'.$count]; }; When I output the code, I seems to have created the specified number of arrays, but has populated all of them with the same data from the last category. Does anyone know where I am going wrong? Thanks, Bernard I have this thing that i am trying to make but i cant get it to work.. can anyone help? Code: [Select] function sql_read( $dbname,$dbusername,$dbpassword ) { $names = array(); $password = array(); $connect = @mysql_connect("mysql11.000webhost.com",$dbusername,$dbpassword) or die("Could Not Connect"); @mysql_select_db ($dbname) or die("Could not find DataBase"); $query = mysql_query("select * from users"); $numrows = mysql_num_rows($query); if ($numrows > 0){ while($row = mysql_fetch_assoc($query)){ $names[] = $row["uname"]; $password[] = $row["password"]; $id = $row["id"]; } $return = array($names,$password,$id); }else{ $return = array(); } return $return[]; } $names = array(); $names = sql_read("XXXXXX","XXXXXX","XXXXXXX")[0]; The error i get is Code: [Select] Parse error: syntax error, unexpected '[' in /home/a5480952/public_html/sql/index.php on line 28 Line 28 is "$names = sql_read("XXXXXX","XXXXXX","XXXXXXX")[0];" Please help... i REALLLLD need help with this.. ask questions if you want to know more about what i am trying to do... thanks! I have two arrays, X and Y, which contain names. The arrays are of the same size. The arrays are related to each other such that for each pair X[n] , Y[n] X is friends with Y. For example: X[0,1,2] = [Link, Cloud, Cloud, Mario, Mario, Luigi] Y[0,1,2] = [Zelda, Barrett, Tifa, Luigi, Bowser, Mario] Link is friends with Zelda Cloud is friends with Barrett and Tifa Mario is friends with Luigi and Bowser Luigi is friends with Mario I want to loop through these arrays and, for each unique name, find all of that person's friends. I then want to print the results to a text file, like so: Link, Zelda Cloud, Barrett, Tifa Mario, Luigi Luigi, Mario I know how to do this theoretically, but I just need help with the PHP syntax. Thanks very much. I have two arrays, both with the same key values. I'd like to combine them. So for instance... Code: [Select] <?php $array1['abcd'] = array( 'value1' => "blah", 'value2' => "blahblah"); $array1['efgh'] = array( 'value1' => "ha", 'value2' => "haha", 'valuex' => "xyz"); $array2['abcd'] = array('value3' => "three", 'value4' => "four"); $array2['efgh'] = array( 'value3' => "hohoho", 'value6' => "six6"); function combine_arrays($array1,$array2) { //*combining* return $single_array; } echo "<pre>"; print_r(combine_arrays($array1,$array2)); echo "</pre>"; /* would produce ['abcd'] = ( 'value1' => "blah", 'value2' => "blahblah", 'value3' => "three", 'value4' => "four" ) ['efgh'] = ( 'value1' => "ha", 'value2' => "haha", 'valuex' => "xyz", 'value3' => "hohoho", 'value6' => "six6" ) */ ?> What's the easiest way to do this? Hello! i want to store data in a array (as seen in the code). Im trying to make it so that a php code search through the arrays and find the correct one. once it does it tells me. I dont know if im close, How ever this is what i have. $carrier = $_POST['carrier']; $carriers = array( array("verizon","tmobile","sprint","att","virgin","textnow","metro","unknown"), array("@vtext.com","@tomomail.net","@messaging.sprintpcs.com","@txt.att.net","@vmobl.com","@textnow.me","@mymetropcs.com","@teleflip.com") ); If ($carrier = hi all, how can i make this array dynamic. E.g, i want the numbers to be pulled from a database... Code: [Select] $s=array( "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" ); thanks in advance, i just cant work it out Hi, I need to do this: Write a method to quickly find the array index position of a given number in a ascending sorted array of numbers. e.g. in an array { 1, 2, 5, 10, 102 }, the array index position of a given number 5, would have an answer of 2. We're looking for an answer that's better than O(n). I was using php's built in methods but I need to do this with a basic function using no helper methods. Can anybody help me out with this? Thanks in advance. Hi, I'm having some trouble trying to generate my random string for a name. This is my code: Code: [Select] <?PHP function rand_string( $length ) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $size = strlen( $chars ); for( $i = 0; $i < $length; $i++ ) { $str .= $chars[ rand( 0, $size - 1 ) ]; } return $str; } $salt_string = rand_string( 5 ); $test = "1234"; echo "salt_string = $salt_string"; echo "<br>"; echo "test = 1234"; echo "<br>"; $array = array('$test', '$salt_string'); echo "<br>"; echo "array = $array"; echo "<br>"; $imploded = implode($array); echo "<br>"; echo "imploded = $imploded"; ?> And it returns: salt_string = 8pbAe test = 1234 array = Array imploded = $test$salt_string I don't understand why my imploded variable is not 12348pbAe Ok i am trying to create a simple program that will allow mwe to use an array with 8 numbers, the output form should show the numbers in their original order that the user inputs them, in numerical order, Highest number, lowest number and then the average number. I am confused on what logic i would use to do this. If anyone could help me get started it would be much appreciated. here's waht i have so far. Code: [Select] <?php $Num1 = $_POST['fielda']; $Num2 = $_POST['fieldb']; $Num3= $_POST['fieldc']; $Num4 = $_POST['fieldd']; $Num5 = $_POST['fielde']; $Num6 = $_POST['fieldf']; $Num7 = $_POST['fieldg']; $Num8 = $_POST['fieldh']; $Numbers = array(1,2,3,4,5,6,7,8); $big = max($Numbers); $small = min($Numbers); $average = array_sum($Numbers) / 8; ?> Hello, I'm trying to extract information about a ticket through osTicket SOAP API, but I can't seem to figure out how! This is the return from the script (var_dump): array(1) { [0]=> object(stdClass)#2 (2) { ["question"]=> object(stdClass)#3 (4) { ["id"]=> int(25) ["created"]=> string(25) "2011-01-05T01:19:43+01:00" ["name"]=> string(4) "test" ["message"]=> string(4) "qasd" } ["answers"]=> array(1) { [0]=> object(stdClass)#4 (4) { ["id"]=> int(25) ["created"]=> string(25) "2011-01-05T01:25:06+01:00" ["name"]=> string(17) "Andreas Haakonsen" ["message"]=> string(3) "ler" } } } } A ticket can have several answers. I just can't seem to figure out how to extract/use this data and present it on my webpage. Too many arrays for me to understand I guess :p Is there anyone who can help me with some small code to help me figure this one out? Thanks! I am trying to learn about sorting and modifying arrays and I am practicing on a book assignment but need some help to grasp what I need to do. If you go here, you will see how it is supposed to work. http://198.86.244.3/mabarckhoff/WEB182/ch11_ex1/ I need to write a case to sort the task when you click the sort button and modify when you click that button. The delete button works and the add task works. I understand the sort array and have added that case, but don't know how to get it to work with the submit. Also there is a promote button so would need 'promote' what ever you have chosen in the dropdown menu to the top. Here is my code. tasklist.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Task List Manager</title> <link rel="stylesheet" type="text/css" href="main.css"/> </head> <body> <div id="page"> <div id="header"> <h1>Task List Manager</h1> </div> <div id="main"> <!-- part 1: the errors --> <?php if (count($errors) > 0) : ?> <h2>Errors:</h2> <ul> <?php foreach($errors as $error) : ?> <li><?php echo $error; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <!-- part 2: the tasks --> <h2>Tasks:</h2> <?php if (count($task_list) == 0) : ?> <p>There are no tasks in the task list.</p> <?php else: ?> <ul> <?php foreach( $task_list as $id => $task ) : ?> <li><?php echo $id + 1 . '. ' . $task; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <br /> <!-- part 3: the add form --> <h2>Add Task:</h2> <form action="." method="post" > <?php foreach( $task_list as $task ) : ?> <input type="hidden" name="tasklist[]" value="<?php echo $task; ?>"/> <?php endforeach; ?> <label>Task:</label> <input type="text" name="newtask" id="newtask"/> <br /> <label> </label> <input type="submit" name="action" value="Add Task"/> </form> <br /> <!-- part 4: the modify/promote/delete form --> <?php if (count($task_list) > 0 && empty($task_to_modify)) : ?> <h2>Select Task:</h2> <form action="." method="post" > <?php foreach( $task_list as $task ) : ?> <input type="hidden" name="tasklist[]" value="<?php echo $task; ?>"/> <?php endforeach; ?> <label>Task:</label> <select name="taskid"> <?php foreach( $task_list as $id => $task ) : ?> <option value="<?php echo $id; ?>"> <?php echo $task; ?> </option> <?php endforeach; ?> </select> <br /> <label> </label> <input type="submit" name="action" value="Modify Task"/> <input type="submit" name="action" value="Promote Task"/> <input type="submit" name="action" value="Delete Task"/> <br /> <label> </label> <input type="submit" name="action" value="Sort Tasks"/> </form> <?php endif; ?> <!-- part 5: the modify save/cancel form --> <?php if (!empty($task_to_modify)) : ?> <h2>Task to Modify:</h2> <form action="." method="post" > <?php foreach( $task_list as $task ) : ?> <input type="hidden" name="tasklist[]" value="<?php echo $task; ?>"/> <?php endforeach; ?> <label>Task:</label> <input type="hidden" name="modifiedtaskid" value="<?php echo $task_index; ?>" /> <input type="text" name="modifiedtask" value="<?php echo $task_to_modify; ?>" /><br /> <label> </label> <input type="submit" name="action" value="Save Changes"/> <input type="submit" name="action" value="Cancel Changes"/> </form> <?php print_r($_POST); ?> <?php endif; ?> </div><!-- end main --> </div><!-- end page --> </body> </html> index.php <?php if (isset($_POST['tasklist'])) { $task_list = $_POST['tasklist']; } else { $task_list = array(); // some hard-coded starting values to make testing easier $task_list[] = 'Write chapter'; $task_list[] = 'Edit chapter'; $task_list[] = 'Proofread chapter'; } $errors = array(); switch( $_POST['action'] ) { case 'Add Task': $new_task = $_POST['newtask']; if (empty($new_task)) { $errors[] = 'The new task cannot be empty.'; } else { $task_list[] = $new_task; } break; case 'Delete Task': $task_index = $_POST['taskid']; unset($task_list[$task_index]); $task_list = array_values($task_list); break; case 'Sort Task': sort($task_list); print_r($task_list); break; /* case 'Save Changes': case 'Cancel Changes': case 'Promote Task': */ } include('task_list.php'); ?> Okay so here is a very simplified version of my code in order to try and illustrate what I am trying to do: $C1 = array (174,30); $C2 = array (165,80); $S = array($C1, $C2); foreach ($S as $cluster) { $number = '5000'; $another_number = '4565'; $cluster[0] = $number; } I feel like this should be really simple but its not working. So basically I'm trying to change the first value of the array select (e.g. C1 or C2) to whatever is in the variable $number. Any help would be greatly appreciated. Thanks Let's say I have an array like this: Man1(0), Man1(1), Man1(2), etc. Man2(0), Man2(1), Man2(2), etc. Man3(0), Man3(1), Man3(2), etc. ... and I want to loop through the array. I know I can do: Code: [Select] $i=0; while $i<=99 {//...do something with Man1[$i];} i++; but can I also do a loop with each Man? Like: Code: [Select] $i=0;$a=1; while $i<=99 {//...do something with Man$a[$i];} i++;a++; I've written all the code for each Man separately and I'm thinking there's got to be a way to shorten the code with another loop, but I don't know how. Hope that makes sense. Thanks. I have ticket's for my lottery system. Somone chooses 3 random numbers out of 36, it will show 1|20|30 but now I want to beable to have my Members BUY multiple Tickets! So then I added a comma between the 3 arrays So the code will look like this when they select the balls they want Code: [Select] 1|20|30,20|10|5 /etc /etc But now I have 1 problem. How do I go about validating the arrays for each COMMA inside the | ARRAY? Cause let's saY I don't want anyone to Submit a ball number higher then "36" how would I go about making it so it checks through each array and if it's higher then 32 I can give them a Error? Also, I each Ticket costs (5 Forum Gold) so the above code would be a total of 10 Forum Gold, because they're "2" Tickets being bought, how would I go about making a $counter++ in the arrays to count only the "," so I can tell how much Gold the member needs to have before he purchases Thanks I can't work out the quotes around this... $bookingID['$row['id']'] = $row['id']; echo $bookingID['$row['id'];']; Parse error: parse error, expecting `']'' What would fix this? |