PHP - Generate Json Structure From Array Of Items
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.
Similar TutorialsI have a table which stores job numbers…each job number can have multiple “line items”…here is a screenshot of example data: https://imgur.com/qSaiJMD I am trying to use another feature of handsontable called nestedRows which makes it look like this: https://imgur.com/lRE6mbq In that example I have setup the JSON with hardcoded data. I am trying to integrate it into my PHP now. I have to make the JSON go from this: https://imgur.com/7hHQvC9 To something like this: https://imgur.com/7bSdl1O I can’t figure out how I can compare the current value in “job_number” to the last row’s “job_number” value so that I can tell the code for example… if($previousRow_job_number == $currentRow_job_number) { //then structure JSON data as a child (line item) of this job number } else { //structure JSON data as a parent job number } This is my current code I am trying to modify: <script type="text/javascript"> /* JSON Construction */ const data = <?php //setup query $sql = 'SELECT * FROM production_data'; //execute SQL transaction try { //prepare SQL statement & execute $stmt = $pdo->prepare($sql); $stmt->execute(); //bind column names to variables $stmt->bindColumn('id', $id); $stmt->bindColumn('job_number', $job_number); $stmt->bindColumn('enterprise', $enterprise); $stmt->bindColumn('part_number', $part_number); $stmt->bindColumn('description', $description); $stmt->bindColumn('qty', $qty); $stmt->bindColumn('line_item', $line_item); $stmt->bindColumn('as400_ship_date', $as400_ship_date); $stmt->bindColumn('date_showed_on_report', $date_showed_on_report); $stmt->bindColumn('shipping_method', $shipping_method); $stmt->bindColumn('notes', $notes); $stmt->bindColumn('date_shown_complete', $date_shown_complete); $stmt->bindColumn('actual_ship_date', $actual_ship_date); $stmt->bindColumn('qty_shipped', $qty_shipped); //output data into spreadsheet view while($row = $stmt->fetch(PDO::FETCH_BOUND)) { //construct array with data $json = array(); while($row = $stmt->fetch(PDO::FETCH_BOUND)) { //$json[] = array($description, $qty, $line_item, $job_number, $as400_ship_date, $date_showed_on_report, "5", $notes, $date_shown_complete, $actual_ship_date, $qty_shipped); $json[] = array($job_number, $line_item, $description, $qty, $as400_ship_date, $date_showed_on_report, "5", $notes, $date_shown_complete, $actual_ship_date, $qty_shipped); } //encode for JSON and output to screen print(json_encode($json)); } } //failed to execute SQL transaction catch (PDOException $e) { print $e->getMessage(); } ?> /* End JSON Construction */ const container = document.getElementById('productionLogTable'); const hot = new Handsontable(container, { data: data, //colHeaders: ['Description', 'Qty', 'LN #', 'Order Number', 'AS400 Ship Date', 'Date Showed on Report', 'Days to Manufacture', 'Notes', 'Date Shown Completed', 'Actual Ship Date', 'Qty Shipped'], colHeaders: ['Job Number', 'LN #', 'Description', 'Qty', 'AS400 Ship Date', 'Date Showed on Report', 'Days to Manufacture', 'Notes', 'Date Shown Completed', 'Actual Ship Date', 'Qty Shipped'], //colWidths: [300, 70, 70, 110, 110, 90, 90, 300, 90, 90], colWidths: [110, 70, 300, 70, 110, 90, 90, 300, 90, 90], rowHeaders: true, headerTooltips: { columns: true, onlyTrimmed: true }, filters: true, dropdownMenu: true, }); </script> I hope I’ve provided enough detail… Edited March 25, 2020 by mongoose00318to make links into actual links Hi, What I'm trying to do is create a script that generates a random list of cars whenever it is run. I have a list of available cars in a MySQL database. I'm just not sure how to get php to generate a list of, say, 20 cars, that are randomly picked from the cars in the database. I may also want to add other statistics like MPG (also already in the database). Can anyone show me how to do this? And is it possible to format the returned data in a table or div format? Thanks in advance Unk Hello all, I have yet again trouble finding a logical solution to my problem. I'm fetching an array which can hold 1 or more values. The problem is, I want these values to ouput in my json_encode function, but this also needs to happen dynamically depending on the amount of values. I can't explain it further, so here's the code so far: Code: (php) [Select] $files = mysql_fetch_array($get_files); $a = count($files); $i = 1; while ($files) { $variablename = 'fileName' . $i; $$variablename = $files['fileName']; $i++; } $output = array( OTHER VALUES , 'fileName1' => $fileName1, 'fileName2' => $fileName2, 'fileName3' => $fileName3, ............); // How do I add the fileNames dynamically depending on how many there are? This got me thinking, I also need to dynamically GET the values with jQuery. How would I do that, when the above eventually works? Thank you. I 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 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? $bl = array(); $link1 = array_rand($cds); $link2 = array_rand($cds); $link3 = array_rand($cds); $link4 = array_rand($cds); $A = 0; while (!in_array($link1, $bl)){ $link1 = array_rand($cds); $bl[$A] = $link1; $A++; } while (!in_array($link2, $bl)){ $link2 = array_rand($cds); $bl[$A] = $link2; $A++; } while (!in_array($link3, $bl)){ $link3 = array_rand($cds); $bl[$A] = $link3; $A++; } while (!in_array($link4, $cds)){ $link4 = array_rand($cds); $bl[$A] = $link4; $A++; } echo $link1; echo $link2; echo $link3; echo $link4; Pretty much I'm trying to generate 4 number's between the min and max of an array but I don't want any duplicates. So it checks if the number exists in a bl array if it does it generates another number, well thats the theory. Doesn't work like that though. 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. Here is how I get categories for article listing. Article can be written in several categories at once. So I have this code: Code: [Select] $category = '1,5,23,46'; //Category IDs $get_cats = explode("," , $category); $cats = ""; for ($i = 0; $i<count($get_cats); $i++ ) { $cat = trim($get_cats[$i]); $catSlug = get_value_of($cat, "inc/cat_ids.php"); $catName = str_replace("-"," ",$catSlug); $cats .= "<a href=\"index.php?category=$catSlug\">".strtoupper($catName)."</a>, "; } $cats = substr($cats,0,-2); As you can see there's get_value_of function that is used to read the category from the file. File is cat_ids.php and looks like this: Quote 1='category-name-1'; 2='category-name-2'; 3='category name-3'; 4='category-name-4'; 5='category-name-5'; etc. I want to improve this in order not to read the file at each step ("for" loop). Means, one can load the file and then generate a list of (links) category compared to the numbers (Ids). So if $category is "1,3,4" I want to get list like this (by reading cat_ids.php): category-name-1, category name-3, category-name-4 With current function I read value for every ID from file in every step. So if article have 10 or more categories script load file 10 or more times. Looking for a solution to do this from a reading file only once. Thanks. 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 } }
I'm trying to set different colors on rows of a table using an array, Problem is I cannot get it to work right, i'm not sure where to place my for loop so that it works right and generates a different color for different row. Code: [Select] $color = array(red,green,blue); while ($row = mysql_fetch_assoc($exec)) { echo '<tr>'; echo '<td>'.$row['brand_name'].'</td>'; echo '<td>'.$row['contact_name'].'</td>'; echo '<td>'.$row['contact_info'].'</td>'; echo '<td>'.$row['email'].'</td>'; echo '<td>'.$row['description'].'</td>'; echo '</tr>'; } I tried putting for loop only for tr, but it didnt work. Code: [Select] for ($i=0;$i<=count($color);$i++) { echo "<tr bgcolor=\"".$color[$i]."\">"; } I cannot put it within the while loop, it'll repeat the rows for all the colors. So where exactly do I place the for loop so that it works right? I have a json file returned by facebook e.g { "data": [ { "name": "Support! Muffin the fool (Oldham Chronicle FAKE)", "category": "Community", "id": "181377645219010", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|181377645219010|MvOBJKYtO7eT8JxMLtJ00HtGNxo" }, { "name": "Northplanet", "category": "Local business", "id": "132483460132622", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|132483460132622|AHXPNTZx7aihyQS_A9W6pR115U4" }, { "name": "Social Media Manger", "category": "Application", "id": "102650199811234", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|102650199811234|KeH0n1OKzZFtCkpa0lX1yJZ7NBE" }, { "name": "Top Ten Things To Remember Me By!", "category": "Application", "id": "375102030458", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|375102030458|H-mpQWrksu_2FzZ_eBNVzeD2Z1Y" } ] } $graph_url = "https://graph.facebook.com/$uid/comments=" . $access_token; $api = json_decode(file_get_contents($graph_url)); $name = $api->data->name; // this bit not storing the name not sure why I am writing a simple connector for an android application and my json_encode is outputting enclosing the array with []. This is throwing an error during the decode process because the array needs to start with a {. I know this has to do with the $output[] in the loop, but I dont know how to pass the values into the array any other way. I even tried to trim after doing the encode. Here is my code: Code: [Select] <?php require_once ('includes/config.php'); require_once ('includes/connect.php'); $agency= mysql_query("SELECT agencyname FROM agency WHERE status ='Prospect' ORDER BY agencyname DESC")or die(mysql_error()); while($ageinfo = mysql_fetch_assoc($agency)) { $output[] = $ageinfo; } print(json_encode($output)); ?> I have a MySQL table with a list of albums and there is a field called "views" with the number of views each album has received. I'm looking to generate an array of all the albums in the table and sort the array by the number of views (descending). I have a list of functions defined in a ContentController.php file. I created a new function called build_albumlist, which I've pasted below. The function "get_ip_log" already exists and works, and I used it as a template to create the "build_albumlist" function: public function build_albumlist(){ return $this->select_raw("SELECT * FROM albums WHERE deleted = '0' ORDER BY views DESC",array(),'all'); } public function get_ip_log(){ return $this->select_raw("SELECT * FROM sessions ORDER BY ID DESC",array(),'all'); } When I use the function, I get this warning: Warning: mysql_real_escape_string() expects parameter 1 to be string, array given inC:\xampp\htdocs\Controllers\DBController.php on line 10 [font=cabin, 'trebuchet ms', helvetica, arial, sans-serif]The "select_raw" function that I used in "build_albumlist" is defined in the DBController.php file, and is defined as below:[/font] private function clean_array($params){ $final=array(); foreach($params as $param){ $final[]=mysql_real_escape_string($param); } return $final; } public function select_raw($query,$params,$type=''){ $query=str_replace("?","'%s'",$query); $final_query= call_user_func_array('sprintf', array_merge((array)$query, $this->clean_array($params))); if($type==''){ $result=mysql_query($final_query) or die(mysql_error()); return mysql_fetch_assoc($result); } elseif($type=='all'){ $result=mysql_query($final_query) or die(mysql_error()); $final=array(); while($row=mysql_fetch_assoc($result)){ $final[]=$row; } return $final; } Does anyone know why the "build_albumlist" function is generating this warning, while the "get_ip_log" is not? Any help would be great, as I am obviously pretty new to this. Been looking to see if anyone has published something like this. I have a number of projects coming up which entail creating input form pages using PHP. Some of these are quite large as to the number of entries, pages etc.. and the worst part is that I know in advance that they most likely will want to change/add to the form after I am done. So rather than coding them physically in the code, I want to define the form elements in an array that I can store in a database/flat file and when the page loads, read from the array to construct the form output. I don't have any issues with dealing with the database or even using arrays, but I have not been able to come up with an array setup that works. Has anyone done this and would care to share the structure they used. Everything that I find on the net is basically sites that want to host the form, but this will be in a non-Internet accessible site so that is not an option. Hi, I'm hoping someone can help me with a simply array problem. I have a table with two columns: "ID" and "Name" and 100 Names. I also have an array called $myIDList containing 10 IDs. I want to display 10 Names from the table that correspond with the IDs from my array. Originally, I tried to implode the array, adding commas and inserted into my MySQL query using: $myQuery = "SELECT ID, Name FROM namesTable WHERE ID IN ($myImplodedIDList)"; The problem was that duplicated names (i.e. the same Name, but assiged to different IDs) would only be displayed once. So now I'm trying to use the original array to loop through a second array and display Names where the ID matches an ID from my first array. I have succesffuly listed the table like this: $myQuery = "SELECT ID, Name FROM myTable ORDER BY ID"; $myResult = mysql_query($myQuery) or die(mysql_error()); while($row=mysql_fetch_array($myResult)) { echo $row['ID']; echo $row['Name']; } But I want to do something like: while($row=mysql_fetch_array($myResult)) { while $row['ID'] = $myIDList { echo $row['Name'] } } Can someone shed some light onto this for me please? Thank you! Bryan Hello everyone. I'm a self learner that is very new to programming. I'm trying to print out the value of ["mid"] from a json_decode variable in the code shown below: I'm trying to use for each to access the value of "mid'. using foreach function. I know I'm not doing it the right way. please help me or show me an easy was to go around it. /////the json resopnd form the url is : {"terms":"http://www.xe.com/legal/dfs.php","privacy":"http://www.xe.com/privacy.php","from":"USD","amount":1.195,"timestamp":"2021-02-09T16:52:00Z","to":[{"quotecurrency":"NGN","mid":454.6559871014}]} ///////////////////////////////////////////////// <?php $auth = base64_encode("username:password"); $context = stream_context_create([ "http" => [ "header" => "Authorization: Basic $auth" ] ]); $homepage = file_get_contents("https://xecdapi.xe.com/v1/convert_from?to=NGN&amount=1.195", false, $context ); $json = json_decode($homepage, TRUE); foreach ($json as $price){ echo $price['mid']; }; ?>
i am brand new to php and thought a project looking at the weather undergound api would be a great place to "cut my teeth" and i am following up on a recent post i saw here http://www.phpfreaks.com/forums/index.php?topic=354658.msg1675207#msg1675207 the responder excellently described how to use the foreach function however i am not sure this is right for my application the project i am trying to accomplish is defining the freeze thaw cycle for the next ten days which i can accomplish in excel but thought this is a good way to learn to code. so my question is how should i do this, i have tried and failed with trying to pick out individual highs and lows data and define them as above or below freezing but i can't figure out how to pick out the right number my code for this part of the project is $json_line = file_get_contents("http://api.wunderground.com/api/{key}/geolookup/forecast10day/q/$zipcode.json"); $parsed_line = json_decode($json_line); echo $parsed_json->{'forecast'}->{'simpleforecast'}->{'forecastday'}->{'date'}->{'weekday'}; $temp_h = $parsed_line->{'forecast'}->{'simpleforecast'}->{'forecastday'}->{'high'}->{'farenheit'}; $temp_l = $parsed_json->{'forecast'}->{'simpleforecast'}->{'forecastday'}->{'low'}->{'farenheit'}; echo "Forecast for ${day} is:\n"; echo "High Temp is ${temp_h}<br />"; echo "Low Temp is ${temp_l}\n"; another road i was looking at going down was trying to do an array shift any help would be greatly appreciated thanks jeremy Havent posted here in a while, been learning lots but im stuck on trying to unset/replace arrays that contain awkward key values.
[0] => 2021-06-02T19:40:00Z [1] => 2021-06-03T02:10:00Z [2] => 2021-06-03T01:10:00Z [3] => 2021-06-02T23:05:00Z [4] => 2021-06-02T23:05:00Z [5] => 2021-06-02T23:07:00Z [6] => 2021-06-02T23:20:00Z [7] => 2021-06-02T18:20:00Z [8] => 2021-06-03T00:10:00Z [9] => 2021-06-03T00:40:00Z The json Im using is constantly updated, not sure why tmrw's dates June 3rd are at the top for their API design =[ Not good at regex. preg_replace/etc. Im desperate id use array search manually if I knew how to simple parse out tmrw's dates. I have unlimited API calls so I reckon it don't matter, here's what Ive been playing with $oddsdata = 'https://pinnacle.datafeeds.net/api/json/odds/pinnacle/v3/60/baseball/mlb/moneyline?api-key=a71b8fe8e9eb957db549aaa5d99797a4'; $readodds = file_get_contents($oddsdata); $odds = json_decode($readodds, true); $today = date("Y-m-d"); $tmrw = date('Y-m-d', strtotime( $today . " +1 days")); foreach($odds['games'] as $key => $val): $gidRE[$key]["gid"] = $val["gameUID"]; $startOdds[$key]["start"] = $val["startDate"]; $homeTeams[$key]["hteam"] = $val["homeTeam"]; $awayTeams[$key]["ateam"] = $val["awayTeam"]; $Price[$key]["betPrice"] = $val["betPrice"]; $BookOdds[$key]["book"] = $val["sportsbook"]; $BetName[$key]["betName"] = $val["betName"]; $Live[$key]["Live"] = $val["isLive"]; endforeach; $endgidd = end(array_keys($gidRE)) + '1'; $endz = end(array_keys($odds['games'])); for ($l = 0; $l < $endz; ++$l) { $OddsAll[] = array_merge($gidRE[$l], $startOdds[$l], $homeTeams[$l], $awayTeams[$l], $Price[$l], $BetName[$l]); }
Hi, I have been banging my head against a brick wall the past few days trying to figure this out after reading so many tutorial and forum post but I still can't figure it out. I would be very grateful if someone could help me out. Basically I am being supplied with this JSON Data structu $json='{ "countries": { "country": [ { "@attributes": { "Name": "Germany", "Lat": "52.6847077739394", "Lng": "-6.81976318359375", "ZoomLevel": "7" } }, { "@attributes": { "Name": "Sweeden", "Lat": "54.00131186464818", "Lng": "-7.36358642578125", "ZoomLevel": "8" } } ] } }'; I decode the JSON data structure as a PHP array and I print out the contents of the array for debugging purposes: $json_array=json_decode($json,true); print_r($json_array); Heres what the outputed array looks like: Code: [Select] Array ( [countries] => Array ( [country] => Array ( [0] => Array ( [@attributes] => Array ( [Name] => Germany [Lat] => 52.6847077739394 [Lng] => -6.81976318359375 [ZoomLevel] => 7 ) ) [1] => Array ( [@attributes] => Array ( [Name] => Sweeden [Lat] => 54.00131186464818 [Lng] => -7.36358642578125 [ZoomLevel] => 8 ) ) ) ) ) I want to be able to access all the country names contained in [Name] Can anyone please help me on how to do this correctly as I've tried lots of code with multi-dimensional arrays but I've had no luck. I am not able to acces the variable correctly. Thanks in advance. |