PHP - Multi Level Drop Down From An Array
I want to have a multi level dropdown selection tool come out of an array (not database; almost all of available codes on the internet are based on mysql databse). I have an array as each element has this format: "Country | City | ID". Using explode, I want to make a dropdown to choose the country, then choosing the cities of the chosen country. Finally, in a simple search box make action="result.php" to lead to result.php?q=$id
Thanks for your kind attention Similar TutorialsHi guys, I'm still not having any luck with coming up with an idea of how to make my multi-level drop down menu work with items from a database. I don't necessarily need code, but an idea of how to make it work, so any ideas are welcome. The table: Column Descriptions: id - The unique id label - The text to display link - The link to be used relation - I cannot remember why I wanted that... just disregard it parent - The parent item's id (0 for no parent) sort - A sort number for the item (ascending) active - 0 for false, 1 for true (not implemented yet, will add a WHERE `active` = 1 into the sql later) depth - How many parent items there are Now, here's what it has to do (the class): Grab items from the database (sorted by depth, parent, and sort) Place the children in a child array of the parents (or however it can be sorted) Implode the array and turn it into an html menu with the below structure Menu HTML Structure Code: [Select] <div id="menu"> <ul> <li><h2>Level 1 A</h2> <ul> <li><a href="?r=level2/a">Level 2 A</a> <ul> <li><a href="?r=level3/a">Level 3 A</a></li> <li><a href="?r=level3/b">Level 3 B</a></li> </ul> </li> </ul> </li> <li><a href="?r=level1/b"><h2>Level 1 B</h2></a></li> </ul> </div> And here is the code I have so far, but I can't figure out how to get the children into the parent array, or at least sort it so that I can achieve the above HTML structure. Thank you in advance for your help, and as I said above, I don't necessarily need code, but an idea of how to make it work, so any ideas are welcome. What am I missing here? The array: protected $form_bonus = array( "Attacker" => array( "Ashwin" => array( "normal" => 1.15, "rps" => 1.38), "Cordelon" => array( "normal" => 1.15, "rps" => 1.38), "Mersan" => array( "normal" => 1.15, "rps" => 1.38), "Phlanixian" => array( "normal" => 1.195, "rps" => 1.494), "Slythe" => array( "normal" => 1.15, "rps" => 1.38) ), "Defender" => array( "Ashwin" => array( "normal" => 1.15, "rps" => 1.38), "Cordelon" => array( "normal" => 1.15, "rps" => 1.38), "Mersan" => array( "normal" => 1.15, "rps" => 1.38), "Phlanixian" => array( "normal" => 1.15, "rps" => 1.38), "Slythe" => array( "normal" => 1.15, "rps" => 1.38) ) ); accessing it: $bonus *= form_bonus[$this->role][$this->race]['rps']; error: PHP Parse error: syntax error, unexpected '[' I want to create an array from a file with this structure TITLE1, HEADER1, key11, key12, key13, key14 TITLE2, HEADER2, key21, key22, key23, key24 . . . How I can get a foreach with these elements: $title="TITLE" $header="HEADER" $key="(one random key)" If needed, I can change the file structure too. $form_bonus = array( "Attacker" => array( "Ashwin" => array( "normal" => 1.15, "rps" => 1.38), "Cordelon" => array( "normal" => 1.15, "rps" => 1.38), "Mersan" => array( "normal" => 1.15, "rps" => 1.38), "Phlanixian" => array( "normal" => 1.195, "rps" => 1.494), "Slythe" => array( "normal" => 1.15, "rps" => 1.38) ), "Defender" => array( "Ashwin" => array( "normal" => 1.15, "rps" => 1.38), "Cordelon" => array( "normal" => 1.15, "rps" => 1.38), "Mersan" => array( "normal" => 1.15, "rps" => 1.38), "Phlanixian" => array( "normal" => 1.15, "rps" => 1.38), "Slythe" => array( "normal" => 1.15, "rps" => 1.38) ) ); echo "<pre>".print_r($form_bonus)."</pre>"; output: 1 what am i missing here? Hi all I have a menu function which basically produces a menu which looks like Code: [Select] Products Apple iMac iPod iPhone Microsoft Windows Office and the code I use is; THE FUNCTION function menu($parentID, $mymenu) { $html = ""; if (isset($mymenu['parentID'][$parentID])) { $html .= " <ul>\n"; foreach ($mymenu['parentID'][$parentID] as $menu_id) { if(!isset($mymenu['parentID'][$menu_id])) { $html .= "<li>\n <a href='/".$mymenu['menu_item'][$menu_id]['url']."'>".$mymenu['menu_item'][$menu_id]['value']."</a>\n</li>"; } if(isset($mymenu['parentID'][$menu_id])) { $html .= "<li>\n <a href='/".$mymenu['menu_item'][$menu_id]['url']."'>".$mymenu['menu_item'][$menu_id]['value']."</a>"; $html .= menu($menu_id, $mymenu); $html .= "</li>"; } } $html .= "</ul>"; } return $html; } CREATE MENU CODE $result = mysql_query("SELECT id, value, url, parentID FROM menu WHERE active = 1 AND deleted = 1 ORDER BY position ASC"); $mymenu = array('menu_item' => array(),'parentID' => array()); while ($menu_item = mysql_fetch_assoc($result)) { $mymenu['menu_item'][$menu_item['id']] = $menu_item; $mymenu['parentID'][$menu_item['parentID']][] = $menu_item['id']; } echo menu(0, $mymenu); The problem I have is the URLS, at the moment the menu URLS are outputted as Code: [Select] Products - http://localhost/Products Apple - http://localhost/Apple iMac - http://localhost/iMac iPod - http://localhost/iPod But I need to alter my function so that URLS are outputted as Code: [Select] Products - http://localhost/Products Apple - http://localhost/Products/Apple iMac - http://localhost/Products/Apple/iMac iPod - http://localhost/Products/Apple/iPod Is this at all possible? Thanks very much everyone John In javascript you can do multiple methods on the same line like: if(document.getElementById('myElement').className.match(/^[0-9]/)){/*Do something*/} in that we have getElementById() and match() on the same line, and it works the same as if you were to split them on multiple lines. Is it possible to do that with php? For example: $obj = new MyObject(); $obj->add(2, 3)->to_string(); db table username------>id->username->cash->points->referrer
db table referral_levels------>id->level->earnings->signupBonusCash->signupBonusPoints->status
username referrer -------- -------- admin kelly88 admin // UPDATE USERNAME ADMIN WITH referral level 1 POINTS/CASH // jacob kelly88 // UPDATE USERNAME ADMIN WITH referral level 2 POINTS/CASH AND USERNAME kelly88 WITH referral level 1 POINTS/CASH // david16 jacob // UPDATE USERNAME ADMIN WITH referral level 3 POINTS/CASH AND USERNAME kelly88 WITH referral level 2 POINTS/CASH AND USERNAME jacob WITH referral level 1 POINTS/CASH //Is this possible. If yes - HOW? Current test registration code with referral level 1 <?php if(!empty($_GET['ref'])){ $referrerUsername = filter_input(INPUT_GET, 'ref', FILTER_SANITIZE_STRING); if(usernameExist($referrerUsername, $db) === TRUE){ $_SESSION['ref'] = $referrerUsername; } } // define variables with the value for each field // the value from POST,GET if this exist, or an empty value $errors = array(); $username = isset($_POST['username']) ? filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING) : ''; $referrer = !empty($_SESSION['ref']) ? $_SESSION['ref'] : (isset($_POST['referrer']) ? filter_input(INPUT_POST, 'referrer', FILTER_SANITIZE_STRING) : ''); if(!empty($_POST['submit'])){ if(empty($username)){ $errors[] = $lang['error']['a_019']; } else if(validUsernameLenght($username) === FALSE){ $errors[] = $lang['error']['a_020']; } else if(validUsernameChars($username) === FALSE){ $errors[] = $lang['error']['a_021']; } else if(usernameExist($username, $db) === TRUE){ $errors[] = $lang['error']['a_022']; } if(!empty($referrer)){ if(usernameExist($referrer, $db) === FALSE){ $errors[] = $lang['error']['a_037']; } else if($username == $referrer){ $errors[] = $lang['error']['a_038']; } } } if(!empty($_POST['submit']) and empty($errors)){ /* $queryOne = 'INSERT INTO users(username, referrer) VALUES (:username, :referrer)'; $insertOne = $db->prepare($queryOne); $insertOne->bindParam(':username', $username, PDO::PARAM_STR); $insertOne->bindParam(':referrer', $referrer, PDO::PARAM_STR); $successOne = $insertOne->execute(); */ if($referrer){ $query = 'SELECT signupBonusCash AS sbc, signupBonusPoints AS sbp FROM referral_levels WHERE level = 1 AND status = "enabled"'; $select = $db->query($query); $row = $select->fetch(PDO::FETCH_ASSOC); $queryTwo = 'UPDATE users SET points = points + :points, cash = cash + :cash WHERE username = :referrer'; $selectTwo = $db->prepare($queryTwo); $selectTwo->bindParam(':cash', $row['sbc'], PDO::PARAM_STR); $selectTwo->bindParam(':points', $row['sbp'], PDO::PARAM_STR); $selectTwo->bindParam(':referrer', $referrer, PDO::PARAM_STR); $selectTwo->execute(); } } if(!empty($errors)){ foreach($errors as $error){ print $error.'<br>'; } } print ' <form method="POST"> <table style="width:100%"> <tr> <td style="width:30%;font-weight:bold">Username</td> <td style="width:70%"><input type="text" name="username" maxlength="255" style="width:200px" value="'.cleanOutput($username).'"></td> </tr>'; if(!empty($_SESSION['ref'])){ print ' <tr> <td style="font-weight:bold">'.$lang['global']['a_047'].'</td> <td><input type="text" name="referrer" readonly="readonly" maxlength="255" style="width:200px" value="'.cleanOutput($referrer).'"></td> </tr>'; }else{ print ' <tr> <td style="font-weight:bold">'.$lang['global']['a_047'].'</td> <td><input type="text" name="referrer" maxlength="255" style="width:200px" value="'.cleanOutput($referrer).'"></td> </tr>'; } print ' <tr> <td colspan="2" style="text-align:center"><input type="submit" name="submit" value="Submit"></td> </tr> </table> </form>'; ?> Mmm i'm not sure if i'm approaching this correctly. Anyways, I wanted to create a multi-level thread, Where the child thread would be after the parent thread. Something like this: Hello World - Hello World - Hi! - What's up? - Hi Bob! Goodbye World - ....This guy got issues - Dude! You should watch Despicable Me! "It's so fuzzy i'm going to dieee!" Anyways, so my table looks something along the line of this: | post id | parent_id | title | body | date | 1 | NULL | Hello | Hi, i'm K | date 2 | NULL | Thread One | Body One | date 3 | 1 | Hello World | Body One | date 4 | 2 | Thread post 4 | Body One | date 5 | 1 | Thread post 5 | Body One | date 6 | 1 | Thread post 6 | Body One | date 7 | 3 | Hi What's up | Body One | date And here's the PHP code, although it's not very neat I want to clean it up and make it neater. I can only go two level deep so far. Any suggestion or recommendations? Using while & for: // Select * Threads $q = "SELECT * FROM test_db ORDER BY post_id ASC"; $r = @mysql_query($q); while ($pid_row = @mysql_fetch_object($r)) { // Array $pid_arr[] = $pid_row->post_id; // Assign Indexes to Post ID $ppid_arr[] = $pid_row->parent_id; // Assign Indexes to ParentID $md_arr = array($pid_arr, $ppid_arr); // Create multi-dimensional array matrix $parent_id = $pid_row->parent_id; } for ($i = 0; $i < count($pid_arr); $i++) { for ($a = 0; $a < count($ppid_arr); $a++) { $pid = $pid_arr[$i]; // pid = post id $ppid = $ppid_arr[$i]; // ppid = parent id //echo "<div>~~ PID $pid ~~ PPID $ppid ~~</div>"; if ($ppid === NULL) { $ppid_is_null = " & parent_id is NULL"; } else { $ppid_is_null = NULL; } // Select Top level Thread $z = "SELECT * FROM test_db WHERE post_id = '$pid'"; $y = @mysql_query($z); while ($t_row = @mysql_fetch_object($y)) { $title = $t_row->title; // title of child thread $level = $t_row->level; // level of child thread...is this useful? } // Display top level thread lvl 1 if ($ppid === NULL) { // If the parent_id is NULL, display top level thread echo '<div>PID: ' . $pid . ' || PPID: ' . $ppid . " || Title: " . $title . "</div><br>\n"; $post = $pid; // PostID = 1 $parent = $ppid; // Parent ID ex: [1] // Get child id, where parent id = [1] // trying to get the child thread here...but it's not working $child_q = "SELECT * FROM test_db WHERE parent_id = '$post'"; $child_r = @mysql_query($child_q); while($c_row = @mysql_fetch_object($child_r)) { $c_arr[] = $c_row->post_id; $c_ppid_arr[] = $c_row->parent_id; } for ($n = 0; $n < count($c_arr); $n++) { if ($c_ppid_arr[$n] === $post) { echo "<div>$c_arr[$n]</div>"; } } break; //echo "<div>PID: $pid</div>"; } break; } } Using While: <?php require_once('db_connection'); echo '<hr><hr><br>'; // I just realized that selecting * where parent id is null might limit the amount of rows retrieved. // Query to select threads $n = NULL; $q = "SELECT * FROM test_db WHERE (test_db.parent_id is NULL) Order By date ASC"; $r = @mysql_query($q); while ($threads = @mysql_fetch_object($r)){ $pid = $threads->post_id; $sid = $threads->subject_id; $parent_id = $threads->parent_id; $title = $threads->title; $body = $threads->body; echo '<div>PostID: ' . $pid . ' || Parent: ' . $parent_id . ' || SubjectID: ' . $sid . ' || Title: ' . $title . ' || Body: ' . $body . '</div>'; $q2 = "SELECT * FROM test_db WHERE parent_id = '$pid' Order by date DESC"; $r2 = @mysql_query($q2); while ($level2 = @mysql_fetch_object($r2)) { $level2_pid = $level2->post_id; $level = 1.5 *($level2->level); // lvl 2: 3em echo '<div style="text-indent:' . $level . 'em">' . 'PostID: ' . $level2->post_id . ' || ParentID: ' . $level2->parent_id . '</div>'; $q3 = "SELECT * FROM test_db WHERE parent_id = '$level2_pid'"; $r3 = @mysql_query($r3); while ($level3 = @mysql_fetch_object($r3)) { $level3 = 1.5 + $level; echo '<div style="text-indent:' . $level3 . 'em">' . 'PostID: ' . $level3->post_id . ' || ParentID: ' . $level3->parent_id . '</div>'; } } } ?> I'm not a comp. sci major or anything, so I'm learning this as I go. Any help would be greatly appreciated. It seems like the while & for is more practical, but i'm not quiet sure. What am I doing wrong? - K I just joined this forum today ^_^ Hope to be good friends with you guys and gals Hi All, I have a function that creates an array using a few sql quereys. I then use the array to output to html. I am wanting to add more data to the array to populate another column in the created table. I am unsure how to add $miqty to the array and then output it in the Qty On Order column. I feel like i need to add the [] to $menuItemsInCat[$mcatname][$miid] = $miname; section but i am not sure where in there it should be.
<?php if (session_status() == PHP_SESSION_NONE) { session_start(); } if (!isset($_SESSION['user_id'])){ header("location: index.php"); exit; } //name of the pagea $_SESSION['this_page'] = 'new-menu'; function getMenuItems($conn){ $output = ''; $stmt = $conn -> query(" SELECT menu_category_name FROM ssm_menu_items INNER JOIN ssm_menu_category on menu_item_category_id = menu_category_id ORDER BY menu_category_display_order "); //create an empty array of all of the menu categories that are in use foreach ($stmt as $item){ $menuItemsInCat[$item['menu_category_name']] = []; } $stmt = $conn -> prepare(" SELECT menu_item_id, menu_item_name, menu_category_name, sum(menu_item_qty) FROM ssm_menu_items mi INNER JOIN ssm_menu_category mcat ON mi.menu_item_category_id = mcat.menu_category_id left join ssm_menu_order USING (menu_item_id) GROUP BY menu_item_id "); $stmt -> execute(); $stmt -> bind_result($miid, $miname, $mcatname, $miqty); while ($row = $stmt -> fetch()) { //put items into the blank array created above under their correct category $menuItemsInCat[$mcatname][$miid] = $miname; } echo "<pre>"; print_r($menuItemsInCat); echo "</pre>"; //foreach thing in $menuItemInCat array there is $menucat array associated with $menuit(ems) array //we want the menu cat foreach ($menuItemsInCat as $menucat => $menuit) { $output .= "<tbody>"; $output .= "<tr class='bg-secondary text-white text-center'><th>$menucat</th>"; $output .= "<th>Qty On Order</th><th>Manage</th></tr>"; //foreach thing in menu items array there is an array of ids and an array of items foreach ($menuit as $itemId => $itemName) { $output .= "<tr><td>$itemName</td>"; $output .= "<td></td>"; $output .= "<td><div class='btn btn-primary'>Manage</div></td></tr>"; } $output .= "</tbody>"; } return $output; } ?> <?php include '_includes/head.php'; ?> <div class="container-fluid"> <div class="row"> <?php include '_includes/header.php'; ?> </div> <div class="row" > <div class="col-sm-2 p-0 bg-dark text-light"> <?php include '_includes/nav.php'; ?> </div> <div class="col-sm-10" style="height: calc(100vh - 80px);overflow:scroll;"> <div class="mt-3"> <table class="table table-striped table-hover table-bordered text-center align-middle"> <?= getMenuItems($conn) ?> </table> </div> <div class="col-sm-12"><?php include '_includes/footer.php'; ?></div> </div> </div> </div> <script> //set sidebar active indicator //XX = name of parent if in dropdown eg "sheet" if(document.getElementById('menu')){ document.getElementById('menu').classList.add('show') } //nav button ID if(document.getElementById('newMenu')){ document.getElementById('newMenu').classList.add('blOrange') } </script> As always your help is very appreciated. Edited February 5, 2020 by AdamhumbugI have a for loop which extracts info from a MySQL table, chooses something then needs to push each bit into an array: for($i = 0 ; $i < $query_report_rows ; ++$i) { $row= mysql_fetch_row($query_names); if($row[6] == 0) { $sName = $row[1]; } elseif($row[6] == 1) { $sName = $row[2]; } $name = "$row[0], $sName"; $print = nl2br($row[7]); } What i need is a multidimensional array to hold $name and $print: $name_print = array( array('name'=>$name 'print'=>$print ) ) How do i array push into such an array from the above for loop? (multi-dimensional array are a very weak point at the moment, so any pointers here would be very much appreciated) I currently have an array that I've built that dumps like this:
0 => array:11 [▼ "category_code" => "123" "category_name" => "Testing" "category_description" => "This is a test category" 19738 => array:5 [▼ "identifier" => "720368842943" "description" => Test Description One "count" => 4 "details" => array:2 [▼ 0 => array:3 [▼ "detail_code" => "2751" "detail_code2" => "43" "detail_specifier" => "Detail One" ] 1 => array:3 [▼ "detail_code" => "2681" "detail_code2" => "9" "detail_specifier" => "Detail Two" ] ] "prices" => array:1 [▼ "01" => "1129.00" ] ] 19739 => array:5 [▼ "identifier" => "720368844121" "description" => "Test Description Two" "count" => 4 "details" => array:2 [▼ 0 => array:3 [▼ "detail_code" => "2751" "detail_code2" => "43" "detail_specifier" => "Detail One" ] 1 => array:3 [▼ "detail_code" => "2681" "detail_code2" => "9" "detail_specifier" => "Detail Two" ] ] "prices" => array:1 [▼ "01" => "1490.00" ] ] I'm using laravel excel in order to export that as an excel file, but it's not quite working the way I intend When it exports to excel I only get the top level info: 123 | Testing | This is a test category But I want to get that info as a header and then each subsequent product for that category as a row, so with the example above it would look like:
123 | Testing | This is a test category Here's the excel code with the array I'm using, which is dumped above: $allCategoryResult= array(); foreach($prices->categories as $category){ $categoryItem = array(); $categoryItem["category_code"] = $category->category_code; $categoryItem["category_name"] = $category->category_name; $categoryItem["category_desc"] = $category->category_desc; foreach($category->skus as $sku){ $skuItem = array(); $skuItem["identifier"] = $sku->sku_info->identifier; $skuItem["description"] = $sku->sku_info->item->description; $skuItem["count"] = $sku->sku_info->item->item_type->count; $skuItem["details"] = array(); foreach ($sku->sku_info->details as $details) { $detailsItem = array(); $detailsItem["detail_code"] = $details->detail_code; $detailsItem["detail_code2"] = $details->detail_code2; $detailsItem["detail_specifier"] = $details->detail_specifier; $skuItem["details"][] = $detailsItem; } $skuItem["prices"] = get_object_vars($sku->prices); $itemCode = $sku->sku_info->item->item_code; $categoryItem[$itemCode] = $skuItem; } $allCategoryResult[] = $categoryItem; } $name = 'Test Export'; $build = Excel::create($name, function ($excel) use ($allCategoryResult) { $excel->setTitle('Test Export'); $excel->sheet('Test Export', function ($sheet) use ($allCategoryResult) { $sheet->fromArray($allCategoryResult);
Hello, I have the following function function make_agent_drop($dropname,$parent=''){ $agents = mysql_query("SELECT * FROM ad_category WHERE cat_status='1' AND parent_id='".(is_numeric($parent)?$parent:"0")."'") or die(mysql_error()); $anum = mysql_num_rows($agents); if($anum>0){ $agentdrop='<select style="width:150px; height:20px; margin-left:100px; font-size:11px;" name="'.$dropname.'" id="'.$dropname.'" class="text" '.(is_numeric($parent)?'':'onchange="update_subcatdrop($(this).val());').'"> <option value="0">Select a Category</option>'; while($row= mysql_fetch_array($agents)){ $agentdrop.='<option value="'.$row['cat_id'].'">'.$row['cat_name'].'</option>'; } $agentdrop.='</select>'; }else{ $agentdrop= 'No '.(is_numeric($parent)?'Sub':'').'Categories Found.'; } return $agentdrop; ; } I creates a drop down from database cats and sub cats.. I am trying to figure out how to add a submit button to dynamically appear when it displays the sub category... Thanks! Dan I am having a hell of a time getting this to work. I need the keys in an array to be specific, not a sequential number or a row in my database. I need to add to the array through each loop of my while() statement. This code does it, but does not use the keys I specify, after the first entry, it starts assigning numbers to keys. Any guidance would be great. <?php require_once ('includes/config.php'); require_once ('includes/connect.php'); $echoarray = array(); $resultsql = mysql_query("SELECT * FROM clients")or die(mysql_error()); while($row = mysql_fetch_array($resultsql)){ if(empty($echoarray)){ $echoarray = array( 'id' => $row['ID'], 'name' => $row['First_Name'] . " " . $row['Last_Name'], 'price' => $row['Status'], 'number' => $row['Sex'], 'address' => $row['Phys_Street'], 'company' => $row['Agency'], 'desc' => $row['Notes'], 'age' => $row['Date_Birth'], 'title' => $row['Occupation'], 'phone' => $row['Phone'], 'email' => $row['Email'], 'zip' => $row['Phys_Zip'], 'country' => $row['Phys_City'] ); } else { array_push($echoarray, $echoarray['id'] = $row['ID'], $echoarray['name'] = $row['First_Name'] . " " . $row['Last_Name'], $echoarray['price'] = $row['Status'], $echoarray['number'] = $row['Sex'], $echoarray['address'] = $row['Phys_Street'], $echoarray['company'] = $row['Agency'], $echoarray['desc'] = $row['Notes'], $echoarray['age'] = $row['Date_Birth'], $echoarray['title'] = $row['Occupation'], $echoarray['phone'] = $row['Phone'], $echoarray['email'] = $row['Email'], $echoarray['zip'] = $row['Phys_Zip'], $echoarray['country'] = $row['Phys_City'] ); } Any Ideas? Hi can anybody help me out with the following problem I am having? I need to populate the key values in the multi-dimentional array structure shown below and the values will be used later in the following way: <tr> <td><?php echo $sm_array[1]['col_1']; ?></td> <td><?php echo $sm_array[1]['col_2']; ?></td> <td><?php echo $sm_array[1]['col_3']; ?></td> <td><?php echo $sm_array[1]['col_4']; ?></td> //and so on, up to 10 </tr> <tr> <td><?php echo $sm_array[2]['col_1']; ?></td> <td><?php echo $sm_array[2]['col_2']; ?></td> <td><?php echo $sm_array[2]['col_3']; ?></td> <td><?php echo $sm_array[2]['col_4']; ?></td> //and so on, up to 10 </tr> This is the array structure, $td->innertext is just a different value each time and is not important for this example, it could essentially be anything: sm_array[$row] = array( "col_1" => $td->innertext, "col_2" => $td->innertext, "col_3" => $td->innertext, "col_4" => $td->innertext, "col_5" => $td->innertext, "col_6" => $td->innertext, "col_7" => $td->innertext, "col_8" => $td->innertext, "col_9" => $td->innertext, "col_10" => $td->innertext, ); But I need to add the values inside a loop, like this: while($row=0; $row<=10; $row++) { $sm_array[$row] = array( "col_".$row => $td->innertext); } But this doesn't allow me to change the key name inside the loop, so for $sm_array[1] there will be 10 keys and their values, and the same for $sm_array[2], it will also have 10 keys and different values for each key and so on! But for some reason the key value will not work this way inside a loop, it doesn't allow "col_".$row and I even tried to echo the key name, like this: while($row=0; $row<=10; $row++) { $sm_array[$row] = array( "<?php echo $row; ?>" => $td->innertext); } It only seems to accept a fixed string or integer as the key, like this: while($row=0; $row<=10; $row++) { $sm_array[$row] = array( "col_1" => $td->innertext); // or like this $sm_array[$row] = array( 1 => $td->innertext); } But then I have a problem, I can't change the key name dynamically! I have tried doing this with conditional staments like this, but it only accepts the first key name and the 2nd, 3rd etc, etc all fail: while($row=0; $row<=10; $row++) { if($row==1){ $sm_array[$row] = array( "col_1" => $td->innertext); }else if($row==2){ $sm_array[$row] = array( "col_2" => $td->innertext); } //and so on } Can somebody please tell me what I am doing wrong or can't this be done or is their some other way of doing this? Thanks in advance Grant I have been trying to solve this problem for a few days now and can't seem to work it out. I'm sure i'm missing some simple point.. I am using a mysql PDO fetch to return 2 fields in each row and then put them into an array of their own: foreach ($st->fetchAll() as $row){ $subs[] = array($row['subscriber'],$row['plant']); Some of the rows share the same $row[0], which is the 'subscriber' field. What I want to do is make up another array with each smaller array having a single, unique $row[0] and any number of added 'plant' fields following (e.g $row[1],$row[2] etc). I've tried all sorts of ways to achieve this but am at a loss. Would someone be able to point me in the right direction ? Thanks. Code: [Select] $i=1; $selected=0; $uservalue=20; $numCols = 3; $numPerCol = ceil(20 / $numCols); echo "<table class=tuble><tr>"; for($col = 1; $col <= $numCols; $col++) { echo "<td>"; for($row = 0; $row < $numPerCol; $row++) { $resultRow = 20; if ($i<=$uservalue) { if ($i == $selected) { $checked = 'checked'; }else{ $checked = ''; } $styles = array( 'Blue Essense' => array('#2B8EFF', '#63CBFF', '50 Forum Gold'), 'veggie' => array('carrot', 'collard', 'pea') ); echo '<input type="radio" value="'.$i.'" name="form[color]">Blue Essence <b><a style="color:#2B8EFF;text-shadow:#63CBFF 2px 1px 1px" href="u.php?id='.$pun_user['id'].'">'.$pun_user['username'].'</a></b><br>'; } else { echo '<label for="s'.$i.'"><input type="radio" value="'.$i.'" name="form[star]" disabled><b><a href="u.php?id='.$pun_user['id'].'">'.$pun_user['username'].'</a></b><br>'; } $i++; } echo "</td>"; } echo "</tr></table>"; Okay, see the $styles array? Code: [Select] $styles = array( 'Blue Essense' => array('#2B8EFF', '#63CBFF', '50 Forum Gold'), 'veggie' => array('carrot', 'collard', 'pea') ); The first is hex code, background, and 2nd is #63CBFF (Front color) and the 3rd is how much it costs I need those arrays to echo out correspondent with my Code: [Select] echo '<input type="radio" value="'.$i.'" name="form[color]">Blue Essense<b><a style="color:#2B8EFF;text-shadow:#63CBFF 2px 1px 1px" href="u.php?id='.$pun_user['id'].'">'.$pun_user['username'].'</a></b> (50 Forum Gold)<br>'; See how the style="color etc/etc" I need to grab the data from $styles to go into the correct spots, Is this feasable? Long story short, I need to explode those arrays out somehow, any idea? i want to edit a product and allocate industries to a product refer following link to view http://meriwebsite.net/envytech/admin/industryallocate.php?pageNum=1SELECT%20a.products_id,%20a.products_image,%20b.language_id,%20b.products_description,%20b.products_name%20%20%20FROM%20products%20a%20,%20products_description%20b%20WHERE%20a.products_id%20=%20b.products_id%20and%20language_id=1%20and%201%20order%20by%20%20b.products_id,%20%20b.products_description I can update prouct name and serial number but cannot get values for industries the do while loop for industry display is given below (displaying industry id before check box here) $iquery="SELECT * from industry "; mysql_select_db($database_DBconnect, $DBconnect); $iResult = mysql_query($iquery, $DBconnect) or die(mysql_error()); $irows = mysql_fetch_assoc($iResult); $itotalrows=mysql_num_rows($iResult); $j=-1; do { $j++; ?> <br /><?php echo "id=". $irows['id'];?><input name="ind[$i][$j]" type="checkbox" class="vardana12" id="ind[$i][$j]" value="<?php echo $irows['id'];?>" /> <?php echo $irows['name'];?> <?php } while ( $irows = mysql_fetch_assoc($iResult) ); ?> I am trying to display values using following code if ( (isset($_POST['sub'] )) or (isset($srno['sub'] ))) { echo "<br> count=".count($_POST['srno']); for($i=0; $i< count($_POST['srno']); $i++){ echo "on 'save' clicked <br>"; echo "<br> products ".$_POST['products_id'][$i]; echo "<br>srno ". $_POST['srno'][$i]; echo "<br>industry ".print_r($_POST['ind'][$i]); echo "<br>product name ". $_POST['products_name'][$i]; Updateindustry($_POST['products_id'][$i], $_POST['srno'][$i],$_POST['industry'][$i],$_POST['products_name'][$i]); } $update=1; $alert= "udation done"; } I am not getting correct values for $_POST['industry'][$i] please help How do I do this? It only does the first nine records and wont cycle through the many records in the second dimension. Thanks. // External Loop is 1 - 9 // Internal Loop is 0 - whatever it is //$muarray_s[0] = $facility_id; //$muarray_d[$external_loop][$interal_loop] = $objfields['139339_date']; //$muarray_t[$external_loop][$interal_loop] = $objfields['139339_time']; //$muarray_i[$external_loop][$interal_loop] = $objfields['139339_main_id']; //$array_of_mu[$external_loop][$interal_loop] = $checklist_item_disc; echo "Begin Draw Runway Image Function <br>"; echo "Establish Array Looping Procedure"; for ($j=0; $j<10; $j=$j+1) { // External Loop // This is actually the Condition not the mu for ($k=0; $k<count($array_of_mu); $k=$k+1) { // Internal Loop // This is the Mu Value; echo "Mu Value is ".$array_of_mu[$j][$k]."<br>"; } } Hi people I need a way to loop through an array where $imgid is some random number assigned to each array element and there are 4 fields id, url, tnurl, caption per array element. I need to extract these 4 fields in the same loop iteration. Thanks Code: [Select] $_SESSION['imagegallery'][$imgid]['id']; $_SESSION['imagegallery'][$imgid]['url']; $_SESSION['imagegallery'][$imgid]['tnurl']; $_SESSION['imagegallery'][$imgid]['caption']; example: Code: [Select] $_SESSION['imagegallery'][347]['id']; $_SESSION['imagegallery'][347]['url']; $_SESSION['imagegallery'][347]['tnurl']; $_SESSION['imagegallery'][347]['caption']; $_SESSION['imagegallery'][892]['id']; $_SESSION['imagegallery'][892]['url']; $_SESSION['imagegallery'][892]['tnurl']; $_SESSION['imagegallery'][892]['caption']; Whats the most efficient way of searching within a multi dimensional array? My Array = Array ( => Array ( => Item 1 [title] => Item 1 [1] => 2012-03-21 [eventDate] => 2012-03-21 [2] => 21 [eventDay] => 21 ) [1] => Array ( => Item 2 [title] => Item 2 [1] => 2012-03-21 [eventDate] => 2012-03-21 [2] => 21 [eventDay] => 21 ) ) String to find = '21' If (MY ARRAY contains STRING TO FIND) {} Clearly in this case there are several '21' (s) so if I only wanted to search the [eventDay] keys...would there be a fast effective and efficient manner? Thoughts and help gratefully received. Will |