PHP - Array Structure Problem -- Probably Elementary
Afternoon Freaks,
I'm trying to add up certain variables inside an array, and keep going around in circles. The array is the result of a mysql SELECT query. I select the contents of a database table, then extract them in php using the following code: Code: [Select] while ( $row = mysql_fetch_assoc($result)) { extract($row); } var_dump($row) outputs the following: Quote Array ( [var1] => 1193 [var2] => 799 [var3] => 805 [var4] => 0.992547 [var5] => 2010-12-20 [var6] => 20 ) Array ( [var1] => 1193 [var2] => 725 [var3] => 725 [var4] => 1 [var5] => 2010-12-20 [var6] => 20 ) Array ( [var1] => 1193 [var2] => 818 [var3] => 850 [var4] => 0.962353 [var5] => 2010-12-20 [var6] => 20 ) Array ( [var1] => 1194 [var2] => 819 [var3] => 860 [var4] => 0.952326 [var5] => 2010-12-20 [var6] => 21 ) Array ( [var1] => 1194 [var2] => 829 [var3] => 870 [var4] => 0.952874 [var5] => 2010-12-20 [var6] => 21 ) Array ( [var1] => 1194 [var2] => 831 [var3] => 870 [var4] => 0.952874 [var5] => 2010-12-20 [var6] => 21 ) What I want is to add up all the var2 values for each var1. e.g., in the case of var1=1193, this would be 799 + 725+ 818. Of course, there are nearly 2,000 var1s (each one with multiple var2s), and I want my computer to do all the work. So I'm trying to isolate each var1 so I can figure out some loop to do this operation. I've tried a bunch of funny little tricks with min(), but keep going in circles. Any ideas? Similar TutorialsI am an ASP.NET developer and I have to call a soap methed written in PBP that takes an argument required an associative array such as $prices = array( 'Tires'=>'test1', 'Spark Plugs'=>'test2' ); can yoiu tell me what the internal representation is of the above I have this array of items in my php file.
$items = array( array("id" => 100,"categorypath" => "level1/powders", "product" => "Mens powder"), array("id" => 200,"categorypath" => "level1/oils/sunflower", "product" => "XYZ oil"), array("id" => 300,"categorypath" => "level1/eatable/vegetables", "product" => "carrot"), array("id" => 400,"categorypath" => "level1/oils/sunflower", "product" => "ABC oil"), array("id" => 500,"categorypath" => "level1/eatable/fruits", "product" => "mango"), array("id" => 600,"categorypath" => "level1/eatable/vegetables", "product" => "spinach"), array("id" => 700,"categorypath" => "level2/baby items/toys", "product" => "puzzle block"), array("id" => 800,"categorypath" => "level2/baby items/toys", "product" => "trucks and cars"), array("id" => 900,"categorypath" => "level2/baby items/clothes", "product" => "shirts"), array("id" => 1000,"categorypath" => "level1/powders", "product" => "Womens powder"), array("id" => 1100,"categorypath" => "level1/oils/groundnut", "product" => "GN oil"), ); Using the above array I am trying to generate a JSON file that will have the following structu
{ "category":[ { "categoryName":"level1", "category":[ { "categoryName":"powders", "products":[ { "id":"100", "path":"level1/powders", "prodname":"Mens powder" }, { "id":"1000", "path":"level1/powders", "prodname":"Womens powder" } ] }, { "categoryName":"oils", "category":[ { "categoryName":"sunflower", "products":[ { "id":"200", "path":"level1/oils/sunflower", "prodname":"XYZ oil" }, { "id":"400", "path":"level1/oils/sunflower", "prodname":"ABC oil" } ] }, { "categoryName":"groundnut", "products":[ { "id":"1100", "path":"level1/oils/groundnut", "prodname":"GN oil" } ] } ] }, { "categoryName":"eatable", "category":[ { "categoryName":"vegetables", "products":[ { "id":"300", "path":"level1/eatable/vegetables", "prodname":"carrot" }, { "id":"600", "path":"level1/eatable/vegetables", "prodname":"spinach" } ] }, { "categoryName":"fruits", "products":[ { "id":"500", "path":"level1/eatable/fruits", "prodname":"mango" } ] } ] } }, { "categoryName":"level2", "category":[ { "categoryName":"baby items", "category":[ { "categoryName":"toys", "products":[ { "id":"700", "path":"level2/baby items/toys", "prodname":"puzzle blocks" }, { "id":"800", "path":"level2/baby items/toys", "prodname":"trucks and cars" } ] }, { "categoryName":"clothes", "products":[ { "id":"900", "path":"level2/baby items/clothes", "prodname":"shirts" } ] } ] } ] } Not being an expert in php, I have somehow managed to reach thus far in my code, but can not quite arrive at the correct logic. Having trouble with handling associative arrays and objects in php. (Javascripting is much easier I feel) So far I have managed to fix all the errors/warning in my code. Here is my full php code:
$items = array( array("id" => 100,"categorypath" => "level1/powders", "product" => "Mens powder"), array("id" => 200,"categorypath" => "level1/oils/sunflower", "product" => "XYZ oil"), array("id" => 300,"categorypath" => "level1/eatable/vegetables", "product" => "carrot"), array("id" => 400,"categorypath" => "level1/oils/sunflower", "product" => "ABC oil"), array("id" => 500,"categorypath" => "level1/eatable/fruits", "product" => "mango"), array("id" => 600,"categorypath" => "level1/eatable/vegetables", "product" => "spinach"), array("id" => 700,"categorypath" => "level2/baby items/toys", "product" => "puzzle block"), array("id" => 800,"categorypath" => "level2/baby items/toys", "product" => "trucks and cars"), array("id" => 900,"categorypath" => "level2/baby items/clothes", "product" => "shirts"), array("id" => 1000,"categorypath" => "level1/powders", "product" => "Womens powder"), array("id" => 1100,"categorypath" => "level1/oils/groundnut", "product" => "GN oil"), ); $jsonStruct = array(); function jsonCreateStruct(){ GLOBAL $items; for($c=0; $c<count($items); $c++){ $categ = $items[$c]["categorypath"]; insertJson($categ, $items[$c]); } } function insertJson($catg, $itm){ GLOBAL $jsonStruct; $exp = explode("/",$catg); print_r("\n\n\n $catg \n"); if(count($exp) == 1){ print_r("Level 1 \n"); if(!isset($jsonStruct[0])){ $jsonStruct[0]["categoryName"] = $exp[0]; $jsonStruct[0]["products"] = array($itm); print_r("\nCreated:: $exp[0]"); }else{ $notFound = true; for($j=0; $j<count($jsonStruct); $j++){ $catgName = $jsonStruct[$j]["categoryName"]; print_r("\nFound: $catgName"); if($catgName == $exp[0]){ $notFound = false; if($jsonStruct[$j]["products"]){ array_push($jsonStruct[$j]["products"],array($itm)); }else{ $jsonStruct[$j]["products"] = array(); array_push($jsonStruct[$j]["products"],array($itm)); } } } if($notFound){ print_r("\nNotFound\n"); array_push($jsonStruct,array("categoryName"=> $exp[0], "products" => array($itm))); } } } if(count($exp) == 2){ print_r("Level 2 \n"); if(!isset($jsonStruct[0])){ $jsonStruct[0]["categoryName"] = $exp[0]; $jsonStruct[0]["categorypath"] = array("categoryName" => $exp[1], "products" => array($itm)); print_r("\nCreated:: $exp[0] / $exp[1]"); }else{ $notFound1 = true; $notFound2 = true; $indexLevel = null; for($j=0; $j<count($jsonStruct); $j++){ $catgName1 = $jsonStruct[$j]["categoryName"]; print_r("\nFound: $catgName1"); if($catgName1 == $exp[0]){ $notFound1 = false; $indexLevel = $j; if(isset($jsonStruct[$j]["categorypath"])){ $level1 = $jsonStruct[$j]["categorypath"]; for($m=0; $m<count($level1); $m++){ if(isset($level1[$m]["categoryName"])){ $catgName2 = $level1[$m]["categoryName"]; print_r("\nFound: $catgName2"); if($catgName2 == $exp[1]){ $notFound2 = false; if($level1[$m]["products"]){ array_push($jsonStruct[$j]["categorypath"][$m]["products"],array($itm)); }else{ $jsonStruct[$j]["categorypath"][$m]["products"] = array(); array_push($jsonStruct[$j]["categorypath"][$m]["products"],array($itm)); } } } } } } } if($notFound1){ print_r("\nNotFound1\n"); array_push($jsonStruct,array("categoryName"=> $exp[0], "categorypath" => array("categoryName" => $exp[1],"products" => array($itm)))); }else if($notFound2){ print_r("\nNotFound2\n"); // $jsonStruct[$indexLevel]["categorypath"] = array("categoryName"=> $exp[1], "products" => array($itm)); $jsonStruct[$indexLevel]["categorypath"] = array(); array_push($jsonStruct[$indexLevel]["categorypath"], array("categoryName"=> $exp[1], "products" => array($itm))); } } } if(count($exp) == 3){ print_r("Level 3 \n"); if(!isset($jsonStruct[0])){ $jsonStruct[0]["categoryName"] = $exp[0]; $jsonStruct[0]["categorypath"] = array("categoryName" => $exp[1], "categorypath" => array("categoryName" => $exp[2], "products" => array($itm))); print_r("\nCreated:: $exp[0] / $exp[1] / $exp[2]"); }else{ $notFound1 = true; $notFound2 = true; $notFound3 = true; $indexLevel1 = null; $indexLevel2 = null; for($j=0; $j<count($jsonStruct); $j++){ $catgName1 = $jsonStruct[$j]["categoryName"]; print_r("\nFound: $catgName1"); if($catgName1 == $exp[0]){ $notFound1 = false; $indexLevel1 = $j; if(isset($jsonStruct[$j]["categorypath"])){ $level2 = $jsonStruct[$j]["categorypath"]; for($m=0; $m<count($level2); $m++){ if(isset($level2[$m]["categoryName"])){ $catgName2 = $level2[$m]["categoryName"]; print_r("\nFound: $catgName2"); if($catgName2 == $exp[1]){ $notFound2 = false; $indexLevel2 = $m; if(isset($level2[$m]["categorypath"])){ $level3 = $level2[$m]["categorypath"]; for($n=0; $n<count($level3); $n++){ //print_r($level3["categoryName"]); if(isset($level3["categoryName"])){ $catgName3 = $level3["categoryName"]; print_r("\ncatgName3: ". $catgName3); if($catgName3 == $exp[2]){ $notFound3 = false; if($level3["products"]){ print_r("\npushing into array\n"); array_push($jsonStruct[$j]["categorypath"][$m]["categorypath"]["products"],array($itm)); }else{ print_r("\ncreate new and pushing into array\n"); $jsonStruct[$j]["categorypath"][$m]["categorypath"][$n]["products"] = array(); array_push($jsonStruct[$j]["categorypath"][$m]["categorypath"]["products"],array($itm)); } } } } } } } } } } } if($notFound1){ print_r("\nNotFound1\n"); array_push($jsonStruct, array("categoryName"=> $exp[0], "categorypath" => array("categoryName" => $exp[1],"products" => array($itm)))); }else if($notFound2){ print_r("\nNotFound2\n"); if(!$jsonStruct[$indexLevel1]["categorypath"]){ $jsonStruct[$indexLevel1]["categorypath"] = array(); } array_push($jsonStruct[$indexLevel1]["categorypath"], array("categoryName"=> $exp[1], "categorypath" => array("categoryName" => $exp[2], "products" => array($itm)))); }else if($notFound3){ print_r("\nNotFound3\n"); //$jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"] = array("categoryName"=> $exp[2], "products" => array($itm)); if(!$jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"]){ $jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"] = array(); } array_push($jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"], array("categoryName"=> $exp[2], "products" => array($itm))); } } } } jsonCreateStruct(); print_r("----------------------------------------"); print_r($jsonStruct); // echo json_encode($jsonStruct);
I have now reached a point where I desperately need help from experts.
I have this code Code: [Select] $nArr = array('A', 'B', 'C', 'D', 'E', 'F'); $counter = 3; while ($counter > 0) { $chunkedValues[$counter][0] = 1; for ($j = 0 ; $j < $counter ; $j++) { $chunkedValues[$counter][$j + 1] = $nArr[$j]; } $nArr = array_slice($nArr, $counter--); } var_dump($chunkedValues); that outputs: Code: [Select] array 3 => array 0 => int 1 1 => string 'A' (length=1) 2 => string 'B' (length=1) 3 => string 'C' (length=1) 2 => array 0 => int 1 1 => string 'D' (length=1) 2 => string 'E' (length=1) 1 => array 0 => int 1 1 => string 'F' (length=1) But i need this index structu Code: [Select] array 0 => array 0 => int 1 1 => string 'A' (length=1) 2 => string 'B' (length=1) 3 => string 'C' (length=1) 1 => array 1 => int 1 2 => string 'D' (length=1) 3 => string 'E' (length=1) 2 => array 2 => int 1 3 => string 'F' (length=1) I want to avoid loops with ceil. Any idea? thanks for your time. When having different levels of directories, using relative paths will not work anymore, for example: controller - authentication File 1: include('../../model/header.php') model File 2: header.php view File 3. style.css The header.php file includes the css file with a relative path, but the problem is it includes it as follows: ../view/style.css When now the header.php file gets included into File 1 in the folder "authentication", then the css file will not be accessible anymore, for it to be accessible you would have to go two directories up. In this sense my question is, what would be the proper path structure for a folder structure with multiple levels? Should I rather use absolute paths, I am not so prone of absolute path. What if the folders changes a bit, or the domain changes, or the location changes? I'm currently looping on an array with this structu Categories{ CategoryName CategoryCode CategoryDescription Products{ product_info{ product_code product_type{ CountNumber ProductDescription } } prices{ "wholesale":"250", "retail":"400" } } }
I'm looping on the above array at each level, and I've declared an array so that I can put all my needed values into it $priceResult = array(); foreach($prices->categories as $category){ $categoryName = $category->category_name; $categoryCode = $category->category_code; $categoryDescription = $category->category_desc; foreach($category->products as $product){ foreach($product->product_info as $info){ $product_code = $info->product_code; foreach($info->product_type as $type){ $CountNumber = $type->CountNumber; $ProductDescription = $type->ProductDescription; } } foreach ($product->prices as $price => $amount) { $price_amount = $amount; } } } The problem I'm having is I don't know how to properly push into that new ```$priceResult``` array so that I can use PHPExcel to put it into a format with a subheader. The format I would want from the above example would be something like this
Test Category 1 | 123 | Category for Testing
Test Category 2 | 321 | New Category for Testing So basically I want to call PHPExcel on my $priceResult array in order to get that format where I can list my category info, and for each product within that category, I'd have a product row. Everything would be grouped by the category main header $build = Excel::create($name, function ($excel) use ($priceResult) { $excel->setTitle('Test Products'); UPDATE:
CategoryCode : 123 CategoryName : TestCategory CategoryDescription: For Testing Products{ 0{ Product_code : 123, CountNumber : 12, ProductDescription: Test Product, price_amount : 150.00 }, 1{ Product_code : 112, CountNumber : 32, ProductDescription: Test Product 2, price_amount : 250.00 } }
Im simply having a problem with structuring a directory structure for mkdir Code: [Select] mkdir("saves/".$worldname."/".$playername, 0777); The middle "/" is causing issues, if I take it out I have no problem in creating a folder name saves/worldnameplayername/ just want to add playername as a sub-dir. I have tried every combination I can think of to get it to accept the divider Any help? First off, I am new to PHP, and want to learn it, but it seems very complicated. Where do I begin? I found a script online for a contact form and I am having trouble making it work for my needs. I wanted to include a phone number field in the email message. This is what I have so far for the PHP, but it does not include the phone field in the body of the message. Everything else works fine. Apologize in advance if this message has been posted many times before. <?php $post = (!empty($_POST)) ? true : false; if($post) { include 'functions.php'; $name = stripslashes($_POST['contactname']); $email = trim($_POST['email']); $subject = "New Message from your website"; $message = stripslashes($_POST['message']); $phone = stripslashes($_POST['phone']); $error = ''; // Check name if(!$name) { $error .= 'Please enter your name.<br />'; } // Check email if(!$email) { $error .= 'Please enter an e-mail address.<br />'; } if($email && !ValidateEmail($email)) { $error .= 'Please enter a valid e-mail address.<br />'; } // Check message (length) if(!$message || strlen($message) < 15) { $error .= "Please enter your message. It should have at least 15 characters.<br />"; } if(!$error) { $mail = mail(WEBMASTER_EMAIL, $subject, $message, "From: ".$name." <".$email.">\r\n" ."Reply-To: ".$email."\r\n" ."X-Mailer: PHP/" . phpversion()); if($mail) { echo 'OK'; } } else { echo '<div class="notification_error">'.$error.'</div>'; } } ?> I have multiple forms within one php file. What is the best structure to use? Code: [Select] if (isset($_POST["one"])) { include... } if (isset($_POST["two"])) { include... } if (isset($_POST["three"])) { include... } OR Code: [Select] if (isset($_POST["one"])) { include... } else if (isset($_POST["two"])) { include... } else if (isset($_POST["three"])) { include... } thanks Hello dear friends, Let say we have Code: [Select] $to = "gigi"; then we have link like this Code: [Select] mysite.com/file.php?id=$1 We can change it to new form by add rule at .htaccess codes Code: [Select] RewriteRule -(.*)\.htm file.php?id=$1 So that the link be like this Code: [Select] mysite.com/$to-$id.htm it will works , Now what if i want to make the link like this Code: [Select] mysite.com/$id/$to.htm what will be the .htaccess code in this way ??? thanks Alright guys.. I need some advice, some recommendations and definitely some help. I've got a submission form for users to upload an image and some basic personal information. The client wanted the information to be divided by the North America (specifically N.A. and not U.S.) and Europe.. so I created a database table with the typical structu a row for the user's name, email, etc. I also added a row labeled "regionid" in which "1" would equal North America and "2" would equal Europe. This "regionid" row would obviously organize the submission by their country. The client specifically wanted to label North America but mentioned only users from the States would probably only submit images, etc. Users could choose if they were submitting a form for US or Europe and "regionid" would be filled by which form was chosen. Recently, the client threw a curveball and now wants Canada as part of the North America submission form. Now, I don't want to add Canada as another option for my "regionid" row because it does belong under North America. However, I need to alter the structure of the database I currently have so that it can now organize if under North America or Europe, and if under North America, if the submission falls under the United States or Canada. I was thinking of adding a drop down menu under the North America form with the options US or Canada. Do you guys have any advice or other directions you would take to solve this problem.. that is, if my situation is even understandable? I found it pretty difficult to explain! Apologies! Hi all, I am working on php project and willing to use the "everything as a plugin" idea so alot of people can easily contribute. I am wondering how I can make a php page that includes my plugins, without having to hardcode them(as in require_once, ...). And afterwards it should be possible to execute a function on each of the enabled plugins. Especially the "hardcode" part I am not sure on how to fix it. As for executing a function for each plugin (so that will be a Class object), I wonder how I can make an object of each class from an interface and then execute a function without hardcoding the creation of all objects. Any one ideas or experience with something like this? Thanks in advance. Hello everyone I want to know why are these functions discouraged because I have a problem ***************** http://mx.php.net/manual/en/function.spliti.php Warning This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged. ***************** I have a long list of standard features of some products (90 features 1800 products) which I am integrating in a CMS. I have to elaborate a CREATE, READ and MODIFY section for the products and I was thinking of using check boxes and if statements with 90 columns in my DB for each feature. (I hope there is an easier way to do this) Before I typed in all the features in one column and splited it with the previous functions mentioned, but it doesn't work for the modify section of the CMS. I am trying to learn a method in which I can easily integrate this 90 standard features in the CMS. Does anyone has a good idea? Hey guys ;-) I got a client that asked me today to create him an MLM type website. The first part of my work would be to test if there system works so I need to run a full demo of the multilevel structure. The MLM structure works as follow: 1 person finds 2 members and they then find 2 more each and so on until we reach 100 level deep. If i got this right, At level 5 there will be 25 members At level 10 there will be 100 members At level 20 there will be 400 members At level 40 there will be 1.600 members At level 100 there will be 10.000 members So at the end of the demo there should be 10k members inserted into the table The table looks like this: id, parent, level, under Parent is the ID of the guy that recruited him, level is the level that guy is at (level 1, 2 , 3, 4 or 5) and under is the number of people under him. I need to run a script that will insert all the data into that table so that we can run some test on the liability of the project so we can set the rates right. At first I thought it would be a piece of cake ... but when I started I found out very fast that populating the MLM network 5 level deep is gona be tricky ... my first attempt gave me a result that looks like this: Code: [Select] |0| |1|2| |x|x|3|4| x|x|x|x|x|x|5|6| As you can see the script only grab the last id then adds 2 new members then uses the last one as the parent and starts over ... So my script is useless and I did not figer out how to do everything in 1 step ... Any help would be appreciated. Hi. I am creating a database where a user can store up to 50 names of their family members. I have two table structures in mind and curious which one is the more efficient structure. ==================================================================================================== TABLE A: userid-firstfamilymemberid-firstfamilymembername-secondfamilymemberid-secondfamilymembername Note:(the columns would repeated until the fiftiethfamilymemberid and fiftiethfamilymembername for a total of 101 columns) TABLE B: userid-familymemberid-familymembername ====================================================================================================== which is more efficient... Table A which would have more columns but less rows or Table B which would have less rows but more columns.. also keep in mind that the fixed amount is 50 family members per a user. Thanks in advance. I'm currently working on a site that has about 4 separate panels on the page that all use an include to populate. Each include is interacting with the database and I'm thinking that it might congest the databse to have each panel connecting to the same data base and getting data when the page loads. I was wondering if it would be good practice to take all the connections and functions and put them on a 5th include at the top of the page. This way the connections and functions would be available to each include. Is this a good idea? Will it be a problem for the 4 includes to ask the php function list include for data? Is it better to just let each include contain only the code it needs? Also, say I have 20 functions on the php include and one site page only needs to use 1 function. Would the php function include still loop thru and connect to the database for all 20 functions just because it is included or will it only use the bandwidth needed to execute the 1 function it is being asked to use? Hope that's not over confusing. Thanks! Hy I have a question. Do you think that the code structure from php affect the SEO? I mean if the application is made in basic php or OOP. thk Hi guys, I am starting out on mvc, I been reading up on it for a bit now.. and I was just wondering if anyone can take a quick look at it and give me some insight on it? maybe some suggestions etc.. I will be using this for a some what medium site when I know that it is good enough to be published. Note that its not done.. in reality I just need to make sure I am heading in the right direction. Hiya, What's the best and most secure way of structuring a website? I have looked at various forum packages (.e.g phpBB, myBB, and smf), and they each seem to use a switch statement in the index.php file. When you go to a section of the website, a "GET" variable is passed, and the relevant area of the website is loaded through the switch statement. Is this the best and only way? I would appreciate any body's thoughts on this topic. Thanks, FishSword Hi all,
I would like some input on database structure for a website that will sell car parts. Necessary fields a
Manufacturer
Part type (eg: exhaust, brakes, engine etc)
Part number
Description
Year & make of vehicle it fits (may need to be separate fields, I don't know, this is my main conundrum) **
Keep in mind, this is a basic example and purely hypothetical at this moment. I haven't done any coding yet.
My main roadblock at the moment is figuring out how to engineer part compatibility in conjunction with a search. Many parts fit many different vehicles. For example, part A123 could fit:
1999-2004 Jetta 2.0
1999-2004 Golf 2.0
1999-2004 Passat 1.9
In your opinion, what would be the most efficient way to store and retreive matching parts? Would I have each model as a separate row? i.e:
row 1: 2002-2004 Jetta ... part A123
row 2: 1999-2004 Golf... part A123
row 3: 1999-2004 Passat... part A123
Basically I would have many duplicate rows where only the year and vehicle model changes. This would definitely work, but would eventually lead to a very large and messy database.
There are already companies that offer a service such as this, but I am looking at looking to sell less products and secondly, in a different language. At the moment, I'm trying to figure out the best way that I could do it. Once I have an idea in mind, then I can decide whether I want to go ahead with that or use a pre-made commercial platform.
HI All, I have noticed that when people show database structure on forums like this one, they have it as a table, like the following:
How do you create this? |