Jump to content

Search the Community

Showing results for tags 'foreach'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hi Freaks I have an update page for an online groundwater information system. I am using Postgresql/PostGIS. This is a screenshot of the update page with 2 select boxes. My problem is I don't want the columns 'well_no' or 'geom' to appear in the first select element, i.e. the column to update, as they should NOT be updated. The code for the first selection drop-down list is as follows: <p> Columns available - select the column to update</p> <form class="my-form" method="post"> <select name='up_column' id='up_column'> <?php try { $result = $pdo->query("select column_name from information_schema.Columns WHERE table_schema = 'public' AND table_name = '{$table}' ORDER BY column_name desc"); foreach ($result as $row) { unset($row['well_no']); unset($row['geom']); echo "<option value={$row['column_name']}>{$row['column_name']}</option>"; } } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } ?> </select> No need to comment that I am not using prepared statements, as I am in a test environment and will rewrite the query before going into production. Please focus on why my use of unset is not working, as both the forbidden columns are appearing in the select list.
  2. I have an existing PHP array ($products) with various fields in it.... id / title / description / link / image link etc. etc. as per requirements for a Google Products feed (https://support.google.com/merchants/answer/7052112). My issue is that, for clothing, Google want a separate record for each size available. My array includes the "size" field as a comma separated list e.g. 6,8,10,12,14 or XS,S,M,L,XL etc. etc. So before creating the feed (a text file, which is currently outputting fine except for the size field issue) I need to duplicate each id where there's more than 1 size in that field, for each size, and then manipulate the fields a little so that (ignoring all the duplicated fields that would remain unchanged) instead of the single record : - id size item group id 52 6,8,10,12,14,16,18,20,22,24,26 I'd have 11 records, item group id would be what the id is, the size appended to the id, and the size field only one (in sequence of those from the original), so: - id size item group id 52-6 6 52 52-8 8 52 . .. ... 52-24 24 52 52-26 26 52 That's just one product....there are quite a lot, each with multiple sizes, but all in the same format within the $products array. As always, any help / pointers / solutions much appreciated!
  3. NOTE - Please read the information first as it contains important information to understand the problem. Rules → • There are 9 Columns(C1,C2,C3,C4,C5,C6,C7,C8,C9) [ Max columns will be 9] • The number of Rows can vary from 3,6,9,12,15,18 (Max). In this case Number of Rows shall be 12 Number of Rows = No of Tickets (Max Allowed 6) x Rows Per Ticket (Max Allowed 3). Thus, Max Rows can be 18 • Each Row is required to have 4 Blank Spaces and 5 Filled with Numbers • All numbers available in the Column Array have to be utilized • This configuration of an shall create a matrix of 9 Columns & 12 Rows (3 x 4 Tickets), which is 108 MATRIX BLOCKS where only a maximum of 60 numbers can be filled out of 108 available blocksrandomly with the above conditions being met 100%. • The numbers in column must be arranged / sorted in ASCENDING ORDER (For coding logic purpose, as soon as the number is assigned to the new MATRIX MAP use array_shift() or unset() the number so as to avoid repetition Example - Row 1 and Column 1 shall generate a MATRIX BLOCK - R1C1 Row 3 and Column 7 shall generate a MATRIX BLOCK - R3C7 Matrix Block can also be termed as Matrix Cell for your ease (if needed) MASTER SET OF ARRAY WITH NUMBERS array( "C1"=> array( 1, 2, 3, 5, 6, 7, 9 ), //7 Numbers "C2"=> array( 13, 14, 15, 17, 18, 19 ), //6 Numbers "C3"=> array( 21, 22, 23, 24, 25, 26, 30 ), //7 Numbers "C4"=> array( 31, 33, 34, 36, 37, 38, 39 ), //7 Numbers "C5"=> array( 41, 42, 46, 47, 48, 49, 50 ), //7 Numbers "C6"=> array( 51, 52, 53, 54, 55, 57, 58 ), //7 Numbers "C7"=> array( 61, 62, 64, 65, 69, 70 ), //6 Numbers "C8"=> array( 71, 74, 75, 76, 77, 78 ), //6 Numbers "C9"=> array( 82, 83, 85, 87, 88, 89, 90 ) //7 Numbers ); The above array has 60 Numbers to be filled out of 108 MATRIX BLOCK / CELL which meets the condition that for a FULL BLOCK containing 4 MINI BLOCKS WITH 3 ROWS (max. allowed) EACH I have been able to generate this without any issue meeting all the conditions of the Columns My Allocation Matrix Array will look like array( "R1"=> array( "C1"=> true, // Means that MATRIX BLOCK R1C1 will be NOT EMPTY "C2"=> false, // Means that MATRIX BLOCK R1C2 will be EMPTY "C3"=> true, "C4"=> false, "C5"=> true, "C6"=> false, "C7"=> true, "C8"=> true, "C9"=> false ), "R2"=> array( "C1"=> false, "C2"=> true, "C3"=> false, "C4"=> true, "C5"=> false, "C6"=> true, "C7"=> true, "C8"=> true, "C9"=> false ), "R3"=> array( "C1"=> true, "C2"=> true, "C3"=> true, "C4"=> true, "C5"=> false, "C6"=> false, "C7"=> false, "C8"=> false, "C9"=> true ), "R4"=> array( "C1"=> true, "C2"=> true, "C3"=> true, "C4"=> false, "C5"=> true, "C6"=> true, "C7"=> false, "C8"=> false, "C9"=> false ), "R5"=> array( "C1"=> false, "C2"=> false, "C3"=> false, "C4"=> false, "C5"=> true, "C6"=> true, "C7"=> true, "C8"=> true, "C9"=> true ), "R6"=> array( "C1"=> true, "C2"=> true, "C3"=> false, "C4"=> true, "C5"=> false, "C6"=> true, "C7"=> false, "C8"=> false, "C9"=> true ), "R7"=> array( "C1"=> false, "C2"=> false, "C3"=> true, "C4"=> false, "C5"=> true, "C6"=> false, "C7"=> true, "C8"=> true, "C9"=> true ), "R8"=> array( "C1"=> true, "C2"=> false, "C3"=> false, "C4"=> true, "C5"=> false, "C6"=> false, "C7"=> true, "C8"=> true, "C9"=> true ), "R9"=> array( "C1"=> true, "C2"=> false, "C3"=> true, "C4"=> false, "C5"=> true, "C6"=> true, "C7"=> false, "C8"=> false, "C9"=> true ), "R10"=> array( "C1"=> false, "C2"=> true, "C3"=> true, "C4"=> true, "C5"=> true, "C6"=> false, "C7"=> true, "C8"=> false, "C9"=> false ), "R11"=> array( "C1"=> false, "C2"=> true, "C3"=> false, "C4"=> true, "C5"=> true, "C6"=> true, "C7"=> false, "C8"=> true, "C9"=> false ), "R12"=> array( "C1"=> true, "C2"=> false, "C3"=> true, "C4"=> true, "C5"=> false, "C6"=> true, "C7"=> false, "C8"=> false, "C9"=> true ) ); In the above array R stands for Row, C for Column, TRUE/FALSE (Boolean) means that if TRUE a Number can be filled in the resulting MATRIX BLOCK / CELL ( Row[Number]Column[Number] ) else if FALSE the MATRIX BLOCK / CELL shall be EMPTY The result for the above shall be PROBLEM : I am unable to understand what should possibly be the logic & loop used here for creating a MATRIX ALLOCATION MAP as shown above I have tried while, foreach & for but unable determine the perfect combination which would meet the conditions. (Tried all of the above with Nested Loops also)
  4. I have a questions table and feedback table. I able to foreach the question header but not the feedback. My code as above: <?php $sql2 = "SELECT DISTINCT[question_id],[q_text] FROM [question]"; $ques = array(); $stmt2 = sqlsrv_query($conn, $sql2, $ques); while ($row = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC)) { $ques[$row['question_id']] = $row['q_text']; } $sql = "SELECT [question_id], [Expr3],[Expr2] FROM [feedback] ORDER BY [Expr2] ASC"; $data = array(); $stmt = sqlsrv_query($conn, $sql); while (list($qid, $a, $eid) = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) { if (!isset($data[$qid][$eid])) { $data[$qid][$eid] = $newArray2; } $data[$qid][$eid][] = $a; } ?> <div class="container"> <?php // produce table header echo "<table border='1' id='table2excel'>\n"; echo "<tr><th>Employee ID</th>"; // loop over array of questions for the header foreach ($ques as $question) { echo "<th>$question</th>"; } echo "</tr>\n"; foreach ($data as $qid => $question) { foreach ($question as $question => $replies) { echo "<tr><td>$question</td>"; foreach (array_keys($ques) as $q_id) { echo "<td>"; echo $replies[$q_id]; echo "</td>"; } echo "</tr>\n"; echo "</tr>\n"; } } echo "</table>\n"; Questions Table: question_id q_text 1 Do you Like Red Color? 02A Do you Like Yellow Color? 02B Do you Like Blue Color? 3 Do you Like Green Color? 4 What color you like among them? 5 Do you Like Purple Color? 6 Do you Like Gold Color? 7 Do you Like Rose Gold Color? 8 Do you Like Black Color? 9 Do you Like Orange Color? The question 4, might be multiple answer. Feedback Table: question_id Expr2 Expr3 1 EMP1001 Yes 02A EMP1001 No 4 EMP1001 Red 4 EMP1001 Yellow 4 EMP1001 Blue 5 EMP1001 No 6 EMP1001 No 3 EMP1001 Yes 02B EMP1001 Yes 7 EMP1001 Yes 8 EMP1001 Yes 9 EMP1001 Yes 1 EMP1002 Yes 02A EMP1002 No 4 EMP1002 Red 5 EMP1002 No 6 EMP1002 Yes 3 EMP1002 Yes 02B EMP1002 Yes 7 EMP1002 No 8 EMP1002 9 EMP1002 Yes Result: Employee ID Do you Like Red Color? Do you Like Yellow Color? Do you Like Blue Color? Do you Like Green Color? What color you like among them? Do you Like Purple Color? Do you Like Gold Color? Do you Like Rose Gold Color? Do you Like Black Color? Do you Like Orange Color? EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 Expected Result: Employee ID Do you Like Red Color? Do you Like Yellow Color? Do you Like Blue Color? Do you Like Green Color? What color you like among them? Do you Like Purple Color? Do you Like Gold Color? Do you Like Rose Gold Color? Do you Like Black Color? Do you Like Orange Color? EMP1001 Yes No Yes Yes Red No No Yes Yes Yes EMP1001 Yes No Yes Yes Yellow No No Yes Yes Yes EMP1001 Yes No Yes Yes Blue No No Yes Yes Yes EMP1002 Yes No Yes Yes Red No Yes No Yes The question id no.4 will allow multiple choice to select, hence there will be multiple feedback for that particular question. foreach.txt
  5. Hi, guys i'm trying to fetch all results from DB through a foreach loop. But it is not working as intended, as it brings only the first record and not the others. here is my code:- $sql1="select * from group_posts"; $stmt_t=$conn->prepare($sql1); $stmt_t->execute(); $data_fetch=$stmt_t->fetchAll(); foreach ($data_fetch as $row_d) { $postid=$row_d['gp_id']; $post_auth=$row_d['author_gp']; $post_type=$row_d['type']; $post_title= html_entity_decode($row_d['title']); $post_data= html_entity_decode($row_d['data']); $data1= array($post_data); // $data1= taggingsys($data0); $post_date=$row_d['pdate']; $post_avatar=$row_d['avatar']; $post_uid=$row_d['user_id']; if ($post_avatar != ""){ $g_pic='user/'.$post_uid.'/'.$post_avatar; } else { $g_pic='img/avatardefault.png'; } $user_image="<img src='{$g_pic}' alt='{$post_auth}' title='{$post_auth}' width='30' height='30'>"; $vote_up_count=$project->voteGroupCheck($postid, $_SESSION['id']); }
  6. Hello. Just a quick question about using a loop to create a string from post variables that will then be used in a query. I have several post variables submitted in a form, some of which contain a value of T. Others are not selected. In the database there are several columns which may contain values of T or may not. I would like to construct a query that searches for specific columns containing T and ignoring the rest. I'm using WHERE "T" IN(colnames). I need to get the column names into a comma separated string. Here's what I'm using: $postVal = array("1", "2", "3", "4", "5"); foreach ($postVal as $key=>$val){ $newVar = “col”.$val; if ($$newVar == "T") { *create/add to comma-separated string } else { *ignore } } I hope that seems clear enough. I'm just not sure if I'm on the right track or not. What do you think? Thank you, in advance!
  7. I have the following in a form that edits values already put into a dbase. $alev = array(1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => 'AP'); $dblev = explode(',',$row['hw_lev']); foreach ($alev as $key => $lev){ if(in_array($lev,$dblev)){ echo "<input type='checkbox' name='ud_lev[]' value='$lev' checked> $lev"; } else { echo "<input type='checkbox' name='ud_lev[]' value='$lev'> $lev"; } When I attempt to edit the dbase values, the following occurs: When I select the "A" checkbox, it is input into the database and reflects in the results. When I attempt to edit this, the "A" box is checked and all is well. When I select anything else AND "A" ("1", "A"), it is input into the database and reflects in the results. When I attempt to edit this, the "1" box is checked but the "A" box is NOT checked. This is what I need. I feel like the problem is with the array? But it could be the loop.. Probably something totally staring me in the face. You know how it goes. I was wondering if you see a problem in the array or in the loop. Any thoughts would be appreciated!
  8. Here's what I'm trying to do. I retrieve results using php foreach loop. Within that loop results, I want to show a div(.show-details) on mouse over only. How do I do that? This is my code so far. <style> .show-details { display: none; } </style> $get_records = $db->prepare("SELECT * FROM records WHERE record_id = :record_id"); $get_records->bindParam(':record_id', $record_id); $get_records->execute(); $result_records = $get_records->fetchAll(PDO::FETCH_ASSOC); if(count($result_records) > 0){ foreach($result_records as $row) { $get_record_title = $row['record_title']; $get_record_details = $row['record_details']; $get_record_price = $row['record_price']; ?> <div class="product"> <div class="product-title"> <?php echo $get_record_title; ?> </div> <div class="product-price"> <?php echo $get_record_price; ?> </div> </div> <div class="show-details"> <?php echo $get_record_details; ?> </div> <?php } } else { echo 'no results.'; } <script> $(document).ready(function() { $(".product").mouseover(function(){ $(".show-details").css("display", "block"); }); }); </script>
  9. foreach($text as $key => $value) { echo "test"; echo "value: " . $value . "<br />"; $tab=explode("\t", trim($value)); echo "<br />" . $tab[0] . $tab[$i1] . $tab[$i2] . $tab[$i3] . $tab[$i4] . $tab[$i5]. "<br />"; ... So this snippet is driving me mad. I'm trying to clean up some code that I've been working on in order to move on to the next segment. When I comment out the "echo value . $value" line, the whole thing 500's on me. I added in the echo test statement just to see if there was something weird going on with the open brace in the foreach statement. Does anyone have any idea why this would be acting this way. More code available upon request, but literally all I'm doing in between saves is adding a // in front of the word echo (I've tried at the very front of the line as well as directly in front of the e in echo with the same results). Thanks.
  10. Hi guys, I have this script I am running, http://pastebin.com/NR1A03hY, works perfectly and does everything I need it to do. The only thing is the redirect at the bottom of the script does not work if line 40 is true. I think I have a problem with my foreach loop and the if statements in-between. Please can someone check, I have no idea on this one! Edit: in the pastebin the redirect is striked out as i was problem solving it. Of course i would not strike it out once its back working! Thanks
  11. Say I have this loop. foreach($record as $row) { <div class="hello">Hello World!</div> } I want to loop through and add a letter alongside the "Hello World!" above. To do that, I found this code. $azRange = range('A', 'Z'); foreach ($azRange as $letter) { print("$letter\n"); } How can I combine the two loops so that I get a result like this? A Hello World! B Hello World! C Hello World! D Hello World! E Hello World! F Hello World!
  12. Hello I have problem to get the whole loop saved in to a file. I seams to save only the last "section" So I have two json files that I decode and managed to echo as I wanted. Now plans changed and I want to save what was echoed in to a file instead. I planned to use file_put_contents for that. My code looks like this but it did not put the whole list in to the file. just one. (I show you only the foreach and attempted file saving. <code> foreach ( $venues as $item){ $s1 = '<li style="padding-top:15px;">' . '<a target="_blank" href="http://foursquare.com/v/' . $item['id'] . '">' . $item['name'] . '</a></li>'; $endpoint2 = 'venues/' . $item['id'] . '/tips'; $params2 = '?limit=1'; $url2 = $base_url.$endpoint2.$params2.$auth; $results2 = file_get_contents($url2); $json_results2 = json_decode($results2,true); $venues2 = $json_results2['response']['tips']['items']; foreach ( $venues2 as $ti){ $s2 = '<li>' . '<span>' . date('j.n.Y',$ti['createdAt']) . '</span>' . ' - ' . $ti['text'] . '</li>'; } } file_put_contents('output.txt',$s1 . $s2); //echo $s1 . $s2; //for quick check </code> If I remove the $s1 and respectively $s2 and put the echo instead I get the whole result on my screen. So why is this only taking the last <li><a href="url and result and so on in to the file? This forum did not allow me to format my text, so appologises for that.
  13. I have to complete a simple task which says 'use foreach to print the value of the sum of two cards, the deck has 16 cards and each card has one number and one colour'. Moreover; I can write four cards and four numbers, but how do I write all sixteen cards (I would prefer if they could sit abreast - parallel to each other)? The code I have so far is this: <?php $a = array( "Red" => 1, "Blue" => 2, "Green" => 3, "Yellow" => 4, ); foreach ($a as $key => $val) { echo "<h4>$key => $val.</h4>"; } ?> // Output: Red => 1. Blue => 2. Green => 3. Yellow => 4.
  14. Hi I try to show lists in random order. I have json that I decode to arrays and loop over it and show the result. Now I have teried to how it in a random order. but no result. tried allready several different ways.. here is something about: $json_results = json_decode($results,true); $groups = $json_results['response']['groups']; echo '<ul>'; shuffle($groups); foreach($groups as $group) It does continue to function, but with no randomizing order. just same as always..please help. Thanks
  15. I am using AJAX to send an array of values to a PHP page that will insert the data into MySQL database. For some reason only the last 5 values are inserted into the MySQL database and I am woundering how to fix that. I am using foreach loop. AJAX Request: Array: [".testimonial", 1119, 316, 1663, 608, "#header", 723, 66, 1663, 608] Posting the array: Sending Array Parameters using " ; " to split. clicks .testimonial;1119;316;1663;608;#header;723;66;1663;608 Source Sent: clicks=.testimonial%3B1119%3B316%3B1663%3B608%3B%23header%3B723%3B66%3B1663%3B608 PHP Page <?php $clicks = $_GET["clicks"]; $clickArray = explode(";",$clicks); $arrays = array_chunk($clickArray, 5); $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "clickmap"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $keys = array('postIdentifier', 'postPos_x', 'postPos_y','postWindowWidth','postWindowHeight'); foreach ($arrays as $array_num => $array) { $values = array(); foreach ($array as $item_num => $item) { $values[] = $item; } $data = array_combine($keys, $values); extract($data); // now your variables are declared with the right values http://php.net/manual/en/function.extract.php $sql = "INSERT INTO data (user_id, identifier_name, pos_x, pos_y, window_width, window_height, status) VALUES ('1', '$postIdentifier', '$postPos_x', '$postPos_y','$postWindowWidth','$postWindowHeight', 'ok')"; } if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?> Is this the correct way of coding it, and why does it post only the last 5 values? Any help would be much appreciated!
  16. Hi everyone, I am still learning PHP, I am getting better a little, but i am still struggle with while and foreach loop to create few columns. I create one column with while or foreach, but I couldn't figure to create few columns intsead of one long column. Can you help me or make any suggest? Thank you so much
  17. Hi, I have a json data, below which contains an item with tax: "date": "2015-05-05 12:41", "shop": "Toto", "products": [ { "price": "2.00", "quantity": "1", "description": "chocolat", "tax": [ { "price": "1.00", "quantity": "1", "description": "tax1" }, { "price": "2.00", "quantity": "1", "description": "tax2" } ] } ] } I am able to calculate the price ($amountAll) with the following code: $datajs = "myJsonSimple2.json"; $datajs = file_get_contents($datajs); $decodageDatajs = json_decode($datajs); $dateBiling = $decodageDatajs->date; $shopName = $decodageDatajs->shop; foreach ($decodageDatajs->products as $obj) { $ItemPrice = $obj->price; $ItemQuantity = $obj->quantity; $ItemDescription = $obj->description; $taxes = (array)$obj->tax; $taxesPrice1 = !empty($taxes[0]) ? $taxes[0]->price : 0.00; $taxesPrice2 = !empty($taxes[1]) ? $taxes[1]->price : 0.00; $taxesQuantity1 = !empty($taxes[0]) ? $taxes[0]->quantity : 0; $taxesQuantity2 = !empty($taxes[1]) ? $taxes[1]->quantity : 0; $taxesDescription1 = !empty($taxes[0]) ? $taxes[0]->description : '1er tax null'; $taxesDescription2 = !empty($taxes[1]) ? $taxes[1]->description : '2e tax null'; $amountAll = $ItemPrice * $ItemQuantity + $taxesPrice1 + $taxesPrice2; } But how I calculate if there are several items (2 or 3 or 5...) { "date": "2015-05-05 12:41", "shop": "Toto", "products": [ { "price": "2.00", "quantity": "1", "description": "chocolat", "tax": [ { "price": "1.00", "quantity": "1", "description": "tax1" }, { "price": "2.00", "quantity": "1", "description": "tax2" } ] }, { "price": "3.00", "quantity": "1", "description": "bonbon", "tax": [ { "price": "2.00", "quantity": "1", "description": "tax1" }, { "price": "3.00", "quantity": "1", "description": "tax2" } ] }, { "price": "2.00", "quantity": "1", "description": "gateaux", "tax": [ { "price": "1.00", "quantity": "1", "description": "tax1" }, { "price": "2.00", "quantity": "1", "description": "tax2" } ] } ] } I need like as : $amountAll = $ItemPrice1 * $ItemQuantity1 + $ItemPrice2 * $ItemQuantity2 + $ItemPrice3 * $ItemQuantity3 + $taxesPrice1a + $taxesPrice2a + $taxesPrice1b + $taxesPrice2b + $taxesPrice1c + $taxesPrice2c; but this is wrong : I must counter and use while statement but I don,t know how I can write ? $calculeItems = count($decodageDatajs->products); $i = 0; while ($i < $calculeItems) { foreach ($decodageDatajs->products as $obj) { $ItemPrice = $obj->price; $ItemQuantity = $obj->quantity; $ItemDescription = $obj->description; $taxes = (array)$obj->tax; $taxesPrice1 = !empty($taxes[0]) ? $taxes[0]->price : 0.00; $taxesPrice2 = !empty($taxes[1]) ? $taxes[1]->price : 0.00; $taxesQuantity1 = !empty($taxes[0]) ? $taxes[0]->quantity : 0; $taxesQuantity2 = !empty($taxes[1]) ? $taxes[1]->quantity : 0; $taxesDescription1 = !empty($taxes[0]) ? $taxes[0]->description : '1er tax null'; $taxesDescription2 = !empty($taxes[1]) ? $taxes[1]->description : '2e tax null'; $amountAll = $ItemPrice * $ItemQuantity + $taxesPrice1 + $taxesPrice2; /* this si wrong !!!!! $amountAll = $ItemPrice1 * $ItemQuantity1 + $ItemPrice2 * $ItemQuantity2 + $ItemPrice3 * $ItemQuantity3 + $taxesPrice1a + $taxesPrice2a + $taxesPrice1b + $taxesPrice2b + $taxesPrice1c + $taxesPrice2c; */ } $i++; } can you help me please Thanks
  18. I am writing a small page in which I want a combo box giving a list of options taken from a database table where the ID from the table is the value and the string is the actual option. I am trying to set it up using a foreach statement, but I keep getting the following error message: Notice: Array to string conversion in issue.php on Line 87. Here is the code I'm using to create this array. First, this is in the beginning of the file to get the array: $sqlStatuses = "SELECT StatusID, Status FROM Status"; try { $rsStatuses = $db->query($sqlStatuses); $arrAllStatus = $rsStatuses->fetchAll(); } catch (Exception $e) { echo $e->getMessage(); } Then in the page body, I am using: <select id="status"> <?php foreach ($arrAllStatus as $statID=>$status) { echo "<option value=\"$statID\"$selected>$status</option>"; } ?> </select> The errors I am getting are on the echo line. Do the variables I use after the "as" have to be the same as the fields in the table? I didn't think so. Chris
  19. Evening everyone and Merry X-Mas (Happy Holidays) or whatever fits you best.... I have been trying over and over for about 12 hours to figure out how to get data from a specific JSON response and assign the specific values to a new array key/value pair. The various ways I have tried to figure this out are numerous so i'm going to avoid the runnig list of "I trieid this...and this...and this... etc etc." just understand I have reached a dead end point where I need help badly. Here is what our end goal is: "The company" is a "service industry" provider (plumbing, electrical etc. etc.) who wants to dispatch its technicians to new jobs based on which technician has the shortest travel time from any existing address where they already have a scheduled appointment that day and has available time in there schedule. Thus the dispatching system when a new service call is entered is going to give "recommended" technicians (up to 4) to be assigned the new service call based on the above mentioned criteria. (Efficient routing to save company gas cost) 1.) We have a "New service" street address assigned to the $to variable: $to = "4813 River Basin Dr S, Jacksonville FL 32207"; 2.) We will have "records" array which containes a series of records, each record consists of a ticket# a technician id# and a street address: $records = array( array("DV1012","30453423","9890 Hutchinson Park Dr Jacksonville, FL 32225"), array("DB3434","30404041","821 Orange Ave Crescent City, FL 32112"), array("DB3434","30605060","1972 Wells Road, Orange Park FL 32073"), array("DB4578","30605060","2 Independent Drive, Jacksonville FL 32202"), array("DB7841","30605060","5000 Norwood Avenue, Jacksonville FL 32208"), array("DB3235","30605060","9501 Arlington Expressway, Jacksonville FL 32225"), array("DB7894","30605060","Massey Avenue, Jacksonville, FL 32227"), array("DB2020","30121212","11200 Central Pkwy Jacksonville, FL 32224") ); 3.) We are going to prepare the records array for submission to Google's Distance Matrix API by URL encoding each array value into a single variable and then submit it: foreach ($records as $key => $value) {$from = $from.urlencode($value[2])."|";} $to = urlencode($to); $data = file_get_contents("//maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&units=imperial&mode=driving&sensor=false"); $res=json_decode($data) or die("Error: Cannot read object"); You may look at the ACTUAL live Google response from this here: http://tiny.cc/i6eerx (We have applied <pre> and var_dump($res) to the output) We are looking to get the following information back: The distance and travel time between the "New Service" address ($to) and each of the address' in the $records array ($from), now once that information is returned from Google (JSON response) we need to parse the response and narrow it down to 4 or less (Based on the 4 lowest drive times) to form a new array which ends like this: $results = array( array("DV1012","30453423","2.3 Miles","8 mins"), array("DB3434","30404041","2.8 Miles","9 mins"), array("DB3434","30605060","4.6 Miles","13.8 mins"), array("DB4578","30605060","5.7 Miles","15.2 min") ); OUR PROBLEM: Everything up until the the Google API response is fine, but iterating over the multidimensional arrays within multidimensional arrays of the JSON response is just not coming together in my head (or 2 dozen code attempts). I am able to ECHO an individual value like ( echo $res->rows[0]->elements[0]->distance->text; ) but this has no value for the end result i need to get to. My last thoughts and efforts was that that I was going to have to embed foreach statements within foreach statements to drill down through the various arrays but that hasn't worked very well and it seems like it shouldn't be how it has to be done. I would appreciate any help in showing me how the iteration code should be written and any explanation about the code so i can wrap my head around it.
  20. I am trying in vain to access the numbers in the "sims" array using the code below, I have tried various numbers of nested foreach loops but get errors every time, can anyone help point me in the correct direction please. Thanks Gordon $stock = (array(1) { ["stock"]=> array(2) { [0]=> array(2) { ["operator"]=> string(3) "ECL" ["sims"]=> array(51) { [0]=> int(8944122650438410000) [1]=> int(8944122650438409000) [2]=> int(8944122650438409000) } } [1]=> array(2) { ["operator"]=> string(2) "JT" ["sims"]=> NULL } } } ) foreach ($stock as $key1 => $item1) { foreach($item1 as $key2 => $item2) { foreach($item2 as $key => $value) { echo $value[sims] . "</br>"; } } }
  21. I have a table called "playlists", and a table called "musics". In the musics table, there is a column playlist_id which references the playlist that each music is contained. I'm using api calls to display information on the site with JavaScript, so I need to return a JSON. I need the json with the following structure: [ Playlists: [ { Name: "etc", musics: [ { name: "teste.mp3" }, { name: "test2.mp3" } ] }, ... ] ] And this is my code: $query = $con->prepare("SELECT * FROM playlists WHERE user_id = :id"); $query->execute(array("id" => $userID)); $playlists = $query->fetchAll(PDO::FETCH_ASSOC); foreach ($playlists as &$key) { $query = $con->prepare("SELECT * FROM musics WHERE playlist_id = :id"); $query->execute(array("id" => $key['ID'])); $songs = $query->fetchAll(PDO::FETCH_ASSOC); $key['musics'] = $songs; } There's a way to avoid this loop?
  22. Can someone tell me why this code will not work? It's supposed to update the quantity in a shopping cart by taking the user input and changing the value of the array. I can add items by clicking the 'add to cart' button, but as you know that only works one at a time. Once you make a selection you have the opportunity to go to the cart and modify the quantity by entering in a numeric value; so instead of clicking 10 times you can just type 1, 0 to get to 10. Is there any other info I can provide to convey what I'm trying to do? I'm new to php so I don't know why it's not working, this looks right according to php.net but something is wrong. if(isset($_POST['submit'])) { foreach($_POST['quantity'] as $key => $value) { if($value==0) { unset($_SESSION['cart'][$key]); }else{ $_SESSION['cart']['$key']['quantity']=$value; } } } errors below: Invalid argument supplied for foreach() illegal string offset 'cart'
  23. Hi, I am trying to create an admin page for a local Gym Club to allow an Administrator to be able to update club prices which then show on different screens on the site. I have been able to display the "Prices Admin" page which basically reads a MySQL database table (pricelist), display the description, member price and non-member price and allows the user to update any of these fields. My problem is that when I try writing the data back to the database with the "UPDATE" statement it fails, what I mean is that nothing updates. I have at the moment commented out the actual update statement and put in a "file_put_contents" command" to try and work out what is in the various fields before the UPDATE is run. I find that the display/INPUT works perfectly well but when I do a foreach on the $record array variable I am getting strange results. I may not have explained this very well but here are the relevant sections of my code; // Display and Input section <div id="admin-area"> <br><br> <a class="admin-left">ADMIN (Class Screen Text & Prices)</a> <br> <div class="admin"> <form name="prices" class="pure-form pure-g " action="?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post"> <fieldset> <textarea id="price-data" name="price-data" rows="5" cols="90"> <?php print(htmlentities($data)) ?> </textarea> <br><br> <label class="pure-u-1-3"> </label> <label class="pure-u-1-3"> <b>Members</b> </label> <label class="pure-u-1-3"> <b>Non-Members</b> </label> <?php $i = 0; while($i < $count) { ?> <input class="pure-u-1-3" id="price_label" type="text" name="records[$i][detail]" value="<?= htmlentities($records[$i]['detail'])?>" maxlength="40" /> <input class="pure-u-1-3" id="price_member" type="text" name="records[$i]" value="<?= htmlentities($records[$i]['price_member'])?>" maxlength="10" placeholder="Member Price" /> <input class="pure-u-1-3" id="price_non" type="text" name="records[$i][nonmember]" value="<?= htmlentities($records[$i]['price_nonmember'])?>" maxlength="10" placeholder="Non Member Price" /> <br> <?php $i++; } ?> <div> <br> <input class="button-input" id="submit" type="submit" name="update" value="Update" /> </div> </fieldset> </form> </div> </div> This results in 11 records displayed on the screen correctly. // In the update section I have removed the actual UPDATE and just used the "put_file_contents()" to show what is in the records array. <?php if (isset($_POST['update'])) { if($_POST['update']=='Update') { file_put_contents('codetest.txt', "File Count - " . $count . "\n", FILE_APPEND); $i = 0; foreach ($_POST[records] as $row) { file_put_contents('codetest.txt', $i . " " . $row['detail'] . " " . $row['member'] . " " . $row['nonmember'] . "\n", FILE_APPEND); $i++; } When run the contents in the codetest.txt is; File Count - 11 0 Party: Airtrack 40.00 30.00 The strange thing here is that the $i = 0 is the first record but the $row['detail'], $row['member'] and $row['nonmember'] details of "Party: Airtrack", 40.00, 30.00 are from record 11 ie the last record. If you want to see the UPDATE code I have been using please let me know and I will post it up here. Any help would be appreciated here. Ian
  24. Is there a nicer, cleaner more efficient and less code way of achieving this? I have an array of rows from the database and 2 of the columns could have either of 2 values which give me 4 possibilities. I want to loop through each of them and assign the row to one of 4 arrays so they are all separated out. This is what i have so far. Haven't tested it yet but the theory makes sense. if(!empty($rows)) { foreach($rows as $key => $row) { switch($row['type']) { case 'post': switch($row['archived']) { case 0: $array1[$key] = $row; break; case 1: $array2[$key] = $row; break; default: } break; case 'event': switch($row['archived']) { case 0: $array3[$key] = $row; break; case 1: $array4[$key] = $row; break; default: } break; default: } } }
  25. Hi guys, Sorry im a bit of a noob when it comes to PHP but I just wondered if someone had an idea on how I could solve this PHP problem. I have a PDO statement that gets all users from a database. With the array of users from the database I create a foreach loop to display all of the users in a table which I want to use to select a specific user, enter a number in the row next to the user I select, then click submit and store the users name and also the number in vairables. I will use this information to populate another database later. My question is, I cant seem to reference the user or the number in the table to extract the user and number I enter. When I try and request the numbered entered in the index.php, it will only ever display a number if I enter a number for a the final user in the table. When I try and view the FullName it never works and I get 'Undefined index: FullName' error. I also specified to 'POST in the form but it doesnt seem to be doing that. Does anyone have any ideas? Thanks //function.php function getRequestors($tableName, $conn) { try { $result = $conn->query("SELECT * FROM $tableName"); return ( $result->rowCount() > 0) ? $result : false; } catch(Exception $e) { return false; } } //form.php <form action "index.php" method "POST" name='form1'> <table border="1" style="width:600px"> <tr> <th>Name</th> <th>Number Entered</th> <tr/> <tr> <?php foreach($users as $user) : ?> <td width="30%" name="FullName"><?php echo $user['FullName']; ?></td> <td width="30%"><input type="int" name="NumberedEntered"></td> <td><input type="submit" value="submit"></td> </tr> <?php endforeach; ?> </table> </form> //index.php if ( $_REQUEST['NumberedEntered']) { echo $_REQUEST['NumberedEntered']; echo $_REQUEST['FullName']; }
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.