PHP - Json Manipulation/filter With Foreach Loop Using Values
I have my data array which i converted to json by splitting the keys using for each loop. Data:
$data = Array ( [table6-ios-camt] => [table6-ios-iamt] => [table6-ios-samt] => [table6-ios-type] => [table6-isd-camt] => 0 [table6-isd-iamt] => 0 [table6-isd-samt] => 0 [table6-isd-type] => [table6-ios-csamt] => [table6-isd-csamt] => 0 [table6-other-camt] => [table6-other-iamt] => [table6-other-samt] => [table6-other-type] => [table6-tran1-camt] => 0 [table6-tran1-iamt] => [table6-tran1-samt] => 0 [table6-tran1-type] => [table6-tran2-camt] => 0 [table6-tran2-iamt] => [table6-tran2-samt] => 0 [table6-tran2-type] => [table6-itc_3b-csamt] => 0 [table6-dump_iog-camt] => [table6-dump_iog-iamt] => [table6-dump_iog-samt] => [table6-dump_iog-type] => [table6-dump_oth-camt] => 4386.09 [table6-dump_oth-iamt] => [table6-dump_oth-samt] => 4386.09 [table6-dump_oth-type] => [table6-itc_clmd-camt] => [table6-itc_clmd-iamt] => [table6-itc_clmd-samt] => [table6-itc_clmd-type] => [table6-total_10-camt] => 4386.09 [table6-total_10-iamt] => 0 [table6-total_10-samt] => 4386.09 [table6-total_10-type] => [table6-total_11-type] => [table6-total_8-csamt] => 0 [table6-total_9-csamt] => 0 [table6-dump_iog-csamt] => [table6-dump_isrc-camt] => [table6-dump_isrc-iamt] => [table6-dump_isrc-samt] => [table6-dump_isrc-type] => [table6-dump_oth-csamt] => [table6-iog_goods-camt] => [table6-iog_goods-iamt] => [table6-iog_goods-samt] => [table6-iog_goods-type] => Capital Goods [table6-itc_clmd-csamt] => [table6-total_10-csamt] => 0 [table6-dump_isrc-csamt] => [table6-iog_goods-csamt] => [table6-iog_inputs-camt] => [table6-iog_inputs-iamt] => [table6-iog_inputs-samt] => [table6-iog_inputs-type] => Input Services [table6-iog_inputs-csamt] => [table6-iog_services-camt] => [table6-iog_services-iamt] => [table6-iog_services-samt] => [table6-iog_services-type] => Input Services [table6-supp_non_rchrg_goods-camt] => [table6-supp_non_rchrg_goods-iamt] => [table6-supp_non_rchrg_goods-samt] => [table6-supp_non_rchrg_goods-type] => Capital Goods [table6-supp_rchrg_reg_goods-camt] => [table6-supp_rchrg_reg_goods-iamt] => [table6-supp_rchrg_reg_goods-samt] => [table6-supp_rchrg_reg_goods-type] => Capital Goods [table6-supp_non_rchrg_goods-csamt] => [table6-supp_non_rchrg_inputs-camt] => 4386.09 [table6-supp_non_rchrg_inputs-iamt] => [table6-supp_non_rchrg_inputs-samt] => 4386.09 [table6-supp_non_rchrg_inputs-type] => Inputs [table6-supp_rchrg_reg_goods-csamt] => [table6-supp_rchrg_reg_inputs-camt] => [table6-supp_rchrg_reg_inputs-iamt] => [table6-supp_rchrg_reg_inputs-samt] => [table6-supp_rchrg_reg_inputs-type] => Input Services [table6-supp_non_rchrg_inputs-csamt] => [table6-supp_rchrg_reg_inputs-csamt] => [table6-supp_rchrg_unreg_goods-camt] => [table6-supp_rchrg_unreg_goods-iamt] => [table6-supp_rchrg_unreg_goods-samt] => [table6-supp_rchrg_unreg_goods-type] => Capital Goods [table6-supp_non_rchrg_services-camt] => [table6-supp_non_rchrg_services-iamt] => [table6-supp_non_rchrg_services-samt] => [table6-supp_non_rchrg_services-type] => Input Services [table6-supp_rchrg_reg_services-camt] => [table6-supp_rchrg_reg_services-iamt] => [table6-supp_rchrg_reg_services-samt] => [table6-supp_rchrg_reg_services-type] => Input Services [table6-supp_rchrg_unreg_goods-csamt] => [table6-supp_rchrg_unreg_inputs-camt] => [table6-supp_rchrg_unreg_inputs-iamt] => [table6-supp_rchrg_unreg_inputs-samt] => [table6-supp_rchrg_unreg_inputs-type] => Input Services [table6-supp_non_rchrg_services-csamt] => [table6-supp_rchrg_reg_services-csamt] => [table6-supp_rchrg_unreg_inputs-csamt] => [table6-supp_rchrg_unreg_services-camt] => [table6-supp_rchrg_unreg_services-iamt] => [table6-supp_rchrg_unreg_services-samt] => [table6-supp_rchrg_unreg_services-type] => Input Services [table6-supp_rchrg_unreg_services-csamt] => ); json: { "table6":{ "ios":{ "camt":0, "iamt":0, "samt":0, "csamt":0 }, "isd":{ "camt":0, "iamt":0, "samt":0, "csamt":0 }, "other":{ "camt":0, "iamt":0, "samt":0, "csamt":0 }, "tran1":{ "camt":0, "iamt":0, "samt":0, "csamt":0 }, "tran2":{ "camt":0, "iamt":0, "samt":0, "csamt":0 }, "itc":{ "camt":0, "iamt":550, "samt":230, "csamt":680 }, "iog":[ { "itc_typ":"cg", "camt":0, "samt":0, "iamt":0, "csamt":0 }, { "itc_typ":"ip", "camt":0, "samt":0, "iamt":0, "csamt":0 }, { "itc_typ":"is", "camt":0, "samt":0, "iamt":0, "csamt":0 } ], "supp_non_rchrg":[ { "itc_typ":"cg", "camt":0, "samt":0, "iamt":0, "csamt":0 }, { "itc_typ":"ip", "camt":4386.09, "samt":4386.09, "iamt":0, "csamt":0 }, { "itc_typ":"is", "camt":0, "samt":0, "iamt":0, "csamt":0 } ], "supp_rchrg_reg":[ { "itc_typ":"cg", "camt":0, "samt":0, "iamt":0, "csamt":0 }, { "itc_typ":"ip", "camt":0, "samt":0, "iamt":0, "csamt":0 }, { "itc_typ":"is", "camt":0, "samt":0, "iamt":0, "csamt":0 } ], "supp_rchrg_unreg":[ { "itc_typ":"cg", "camt":0, "samt":0, "iamt":0, "csamt":0 }, { "itc_typ":"ip", "camt":0, "samt":0, "iamt":0, "csamt":0 }, { "itc_typ":"is", "camt":0, "samt":0, "iamt":0, "csamt":0 } ] } }
Keeping in mind the following conditions: 1.If all the keys in the objects are 0 then the entire object will be removed (easy part). 2.If a key in the object has any value other than 0 , the object should not be removed and the key with "0" value should also be there.i've tried splitting value and using conditions to check for 0 or null values but the problem with that is it removes all keys that have 0 values thus failing condition 2 for the code. $vars = $data; $count = ""; $finalArray = array(); foreach ($vars as $keys => $values) { foreach ($values as $k => $v) { foreach ($v as $ke => $ve) { if ($keys == "table6") { $count = (array)$v; foreach ($count as $ck => $cv) { if ($cv != "0") { $flag = true; break; } } if($flag == false) { array_push($finalArray, $count); } } } } print_r($finalArray); die(); I expeced the output to contain the objects with key value pairs that does not contain 0 value but everything prints here. Similar TutorialsHey there folks, Im trying to get a foreach loop working correctly from a json source epg heres my code: https://pastebin.com/FjHj1EF6 Here is the current output, which.. while correct is only the first instance of these values i wanted using the foreach loop, i would love any tips on why my approach failed and to be pointed in the right direction. While it has to be included: $url = "https://mywebsite.fake/mlb.php?id={$arr['games'][0]["gamePk"]}"; this value isn't related to the assistance im asking for. that will work for my purposes later. but for now i just need to understand the issue with the foreach loop. Thanks in advance for your thoughtful response. mosb3rgler Hi.. I have table which has a data so_month: FromMonth : 5 ToMonth : 7 and I have table working_days: MonthName May Jun Jul MonthNumber 05 06 07 WorkingDays 23 24 23 Now I have function to get the 3 consecutive months from FromMonth to ToMonth , which as you can see from May to Jul Now I have problem in getting the SUM of Working days. here is my code: <?php $sql = "SELECT FromMonth, ToMonth FROM so_month"; $res = mysql_query($sql,$con); $row = mysql_fetch_assoc($res); $FromMonth = $row['FromMonth']; $ToMonth = $row['ToMonth']; function monthNames($from, $to){ $range=array(); for($i=$from; $i<=$to; $i++){ $range[$i]=date('M', mktime(0,0,0,$i)); } return $range; } $month_ = implode("' ', ",monthNames($FromMonth,$ToMonth)); foreach( monthNames($FromMonth, $ToMonth) as $month){ $sql = "SELECT MonthName, SUM(WorkingDays) AS WorkingDays FROM working_days WHERE MonthName IN ('$month') GROUP BY MonthName"; $res = mysql_query($sql, $con); while($row = mysql_fetch_array($res)){ $WorkingDays = $row['WorkingDays']; } echo $WorkingDays; } ?> the output of this code is: 232423 and when I change this line: $WorkingDays = $row['WorkingDays']; to $WorkingDays += $row['WorkingDays']; the output is: 234770 I correct output should be: 70 Any help is highly appreciated. Thank you very much.. Hi I am new this forum and looking for some much appreciated help with something that has me stumped. I have extracted regions from image names in a directory. example: 'edinburgh_castle_(Edinburgh).jpg' (Extracted Edinburgh from in-between the brackets) So I have a list of Regions, extracted from all the various image names in the directory which I want to populate into a dynamic drop down menu for filtering purposes. Here's my issue... I want there to be only one 'Edinburgh' option appearing in my drop down menu. I don't want duplicates. Here is my code so far. php: [Select]
hi, i’m currently facing a new problem (i managed to use array_unique function successfully but i face this problem)with my php loop. i couldn’t seem to increment in my foreach loop to get the value of an array. $update_id1=Array ( [0] => 398 [1] => 397 [2] => 393 [3] => 391 [8] => ); //$i=0; foreach ($update_id1 as $i => $v) { $ex= explode(",", $v); $unique=array_unique($ex); //f$ketch username from update table in db and inject it to the feed query. $imp_id= implode(',', $ids); //$id1=$ids[$i]; // $x=0; // for($x=0;$x<count(unique);$x++){ echo 'ids:- '.$i; print_r($unique[$i]); echo '<br>'; //} $totalUpdates=$project->totalUpdates($ids[$i],$_SESSION['uname'] ,$unique[$i],$load); //$i++; } i tried every method nothing seems to work can anyone help me in this regard please. Edited December 25, 2019 by narutofanI have a database query set up that returns an array. I then cycle through the rows in a foreach statement that wraps each value in a <td> tag to output it to a table. It works really great, but now I need to access two of the values and add some info to them. The first field returned is an image filename and I want to wrap it in an image tag that also concatenates the image path location to the value. All the images are stored in the same location, so basically I want to take the first value form the array and add the path to where the images are and wrap the whole thing in an <img> tag. The other field I need to modify is the last value in the array which is actually an email address. For that field I want to make them an active email link so I need to wrap an <a>href=mailto: </a> tag around the value. How could I modify this code so I could add the necessary tags to these elements of the array? Here is the code I am running: Code: [Select] $query = "Select member_image as 'Image', member_name as 'Name', city as 'City', phone as 'Phone', email as 'Email' FROM directory"; //connect to database $conn=db_connect(); //call function do_query to run the query and output the table do_query($conn, $querey); The functions called are as follows: Code: [Select] function db_connect() { $conn = new mysqli("localhost", "username", "password", "databasename"); } function do_query($conn, $query); { $result = mysqli_query($conn, $query); WHILE ($row = mysqli_fetch_assoc($result)) { If (!$heading) //only do if header row hasn't been output yet { $heading = TRUE; //so we only do it once echo "<table>\n<tr<>\n"; foreach ($row as $key => $val) { echo "<th>$key</th>"; } echo "</tr>\n"; } echo "<tr>"; foreach ($row as $val) { echo "<td> $val </td>"; } echo "</tr>\n"; } //close the while echo "</table>\n"; } 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]); }
Hello guy, Just wanted to see how I could resolve this issue I have a foreach loop here that will spit out the vars. Code: [Select] foreach (array_keys($_POST) as $key) { $$key = $_POST[$key]; print "$key is ${$key}<br />"; } echo "<br><br><br>This is the viewname" . $viewname; echo "<br><br><br>This is the price" . $price; I am trying to run the post vars through a filter (The filter name is filter($value) but I cant get it to work. I tried this Code: [Select] foreach (array_keys($_POST) as $key) { $$key = $_POST[$key]; $$key = filter($value); print "$key is ${$key}<br />"; } echo "<br><br><br>This is the viewname" . $viewname; echo "<br><br><br>This is the price" . $price; Any ideas? Thanks, Dan Below is my output on the browser: Student: Kevin Smith (u0867587) Course: INFO101 - Bsc Information Communication Technology Course Mark 70 Grade Year: 3 Module: CHI2550 - Modern Database Applications Module Mark: 41 Mark Percentage: 68 Grade: B Session: AAB Session Mark: 72 Session Weight Contribution 20% Session: AAE Session Mark: 67 Session Weight Contribution 40% Module: CHI2513 - Systems Strategy Module Mark: 31 Mark Percentage: 62 Grade: B Session: AAD Session Mark: 61 Session Weight Contribution 50% Now where it says course mark above it says 70. This is incorrect as it should be 65 (The average between the module marks percentage should be 65 in the example above) but for some stange reason I can get the answer 65. I have a variable called $courseMark and that does the calculation. Now if the $courseMark is echo outside the where loop, then it will equal 65 but if it is put in while loop where I want the variable to be displayed, then it adds up to 70. Why does it do this. Below is the code: Code: [Select] $sessionMark = 0; $sessionWeight = 0; $courseMark = 0; $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { $sessionMark += round($row['Mark'] / 100 * $row['SessionWeight']); $sessionWeight += ($row['SessionWeight']); $courseMark = ($sessionMark / $sessionWeight * 100); if($studentId != $row['StudentUsername']) { //Student has changed $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n"; } if($courseId != $row['CourseId']) { //Course has changed $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong>" round($courseMark) "<strong>Grade</strong> <br><strong>Year:</strong> {$row['Year']}</p>\n"; } if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } //Get output for last module $output .= outputModule($moduleId, $moduleName, $sessionsAry); //Display the output echo $output; I think the problem is that it is outputting the answer of the calculation only for the first session mark. How in the while loop can I do it so it doesn't display it for the first mark only but for all the session marks so that it ends up showing the correct answer 65 and not 72? i am trying to get values from the json array that get direct messages from twitter but i am getting the message error "Parse error: syntax error, unexpected T_AS, expecting '(' " in relation to the line "foreach (array as $direct_message) {" Also should i convert the array into a linear php array? Code: [Select] // create new instance $OAuth = new TwitterOAuth($consumer_key,$consumer_secret, $oAuthToken, $oAuthSecret); $direct_message = $OAuth->get('https://api.twitter.com/1/direct_messages.json?count=1&page='); function write_into_database ($direct_message) { $conn = mysql_connect("127.0.0.1", "Diego", "frafra") or die(mysql_error()); mysql_select_db('bot', $conn) or die(mysql_error()); foreach(array as $direct_message) { mysql_query("INSERT INTO 'followers' ('user_id', 'user_alias'), VALUES ('{$direct_message->sender_id}', '{$direct_message->sender_screen_name}, INSERT INTO 'd_messages'('message_id', 'message'), VALUES ('{$direct_message->id}' ,'{$direct_message->text})"); } write_into_database($direct_message); This is more of a database architect question.
I am building a CMS for website development. I am ready to use it for the first time on one of my clients. Now, my issue is is how to set up some or one of my table(s) for some areas that my client wants to be able to change in the admin section.
In their website on the front page, I put together this nice block slider. Its 6 blocks with text, a background image and nice effects. At first it was always going to be static, which was no issue at all, but later they came to me and asked if they could be able to change words in the boxes themselves in the admin section..
Of course this can be easily done by creating a table that is associated with this home page block thing and each row in the table will correspond to one of the blocks on the home page.
But I believe there might be an easier way to store this type of data without having to create another table for every feature the client wants to edit, for example they also want to be able to edit a slider on another page.
The WordPress database then came into my mind and how they store most of their data as JSON. So I was then thinking of creating a table named 'modules' for examples with three columns (id, title, data). Then inside the data column store the editable fields as a JSON string object.
For example a row could like like :
1, "Front Page Box Slider", {"slider-home" : [ {"data" : "value", "img_1", "value1"}, {"data" : "value", "img_2", "value2"} ]}
I've been doing a bit of research on this and people have just been saying, never do this if you do want your data to be searched through, which I don't.
Can anyone tell me why or why not I should do this, or maybe a better solution to my problem?
Thank you
Edited by carlosmoreeira, 17 September 2014 - 07:37 PM. hello, i want to extract the sender_id, sender_alias and text from the array that should be returned when requesting access to direct messages via API. I get the error "Fatal error: Call to undefined method TwitterOAuth::request() " referring to the line $direct_message = $OAuth->request('GET', $OAuth->url('https://api.twitter.com/1/direct_messages.json'), array('sender_id','screen_name' ,'text')); Code: [Select] // create new instance $OAuth = new TwitterOAuth($consumer_key,$consumer_secret, $oAuthToken, $oAuthSecret); $direct_message = $OAuth->request('GET', $OAuth->url('https://api.twitter.com/1/direct_messages.json'), array('sender_id','screen_name' ,'text')); $direct_message = json_decode($OAuth->response['response'], true); echo response; Hello, Having a bit of a tough time understanding what is going on in my brain! I'm basically pulling some data from an API using CuRL, which is working fine. The structure of the data is: [data][tickets] - tickets being an array of support tickets in the system, which then contains ticketNumber, title, content. I want to display these values in a list, I have this code currently: if ($err) { echo "cURL Error #:" . $err; } else { $return = json_decode($response, true); foreach($return as $key) { echo $key["tickets"][1]['ticketNumber']." - "; echo $key["tickets"][1]['title']." - "; echo $key["tickets"][1]['content']; } } Which obviously returns the ticketNumber, title & content of the first support ticket in the array, but I want to loop through and display that information for each ticket! Can anyone advise as to where I am going wrong? I think I need to utilise the ["tickets"][x] but not sure how!
Thanks in advance! Steve I 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 Hey guys, Got another question im hoping someone can help me with. I have a foreach loop (for use in a mysql query): foreach ($interests as $interest) { $query .= "($id, $interest), "; } problem is i do not want the comma(,) in the last loop. Is there some kinda of function i can use so it does not insert it on last loop? Or should i just use a for loop with a nested if loop? something like ; for($i=0; $i < count($interests); $i++){ $query .= "($id, '$interests[$i]')"; if($i + 1 < count($interests)) { $query .= ", "; } } Cheers guys Hey guys, need help on some addition. foreach($login as $line_num => $line) { $login = explode(" ", htmlspecialchars(str_replace(" "," ",$line))); if(stristr($login[1], "\n")) $login[1] = substr($login[1], 0, strlen($login[1])-2); $account_data[$line_num] = array($login[0], $login[1]); $UserID = $login[0]; $AuthKey = $login[1]; $MobLink = "http://mobsters-fb-apache-dynamic-lb.playdom.com/mob_fb/"; $RefreshStat = file_get_contents($MobLink."refresh_stat_manual?user_id=".$UserID."&auth_key=".$AuthKey); $Cash = explode ("<cash>", $RefreshStat); $Cash = explode ("<", $Cash[1]); $Cash = $Cash[0]; $CashForEcho = "$".number_format($Cash[0]); echo $CashForEcho."<br/>"; echo "<br/><br/>"; } The variable $Cash will be dynamic for each user I put in the $login_file, and I need to add all of those values up. So say I put in 3 users within the $login_file, and the $Cash for user 1 was $3,000, the $cash for user 2 was $6,000 and the $cash for user 3 was $1,000, I want to be able to automatically add them all up, so it would echo '$10,000' at the end. Hope I've explained it for you guys to understand easily enough, if not let me know. Thanks Does anybody know how to make the following code correct? real sorry but its just absolutely blowing my mind im awful with loops and have pretty much no clue what the hell im doing in honesty, any help would be great, Thanks Code: [Select] $addIDs_ary = array_map('intval', $_POST['chkInv']); $addIDs_ary = array_filter($addIDs_ary); $value = $addIDs_ary; //Check if hit_id is already in hitlist $query = mysql_query("SELECT * FROM hitlist WHERE player_id = '$playerID'"); $result = mysql_query($query); while ($result = mysql_fetch_assoc($result)) foreach ($result as $hit_id => $value){ if($result[$hit_id] == $value); $str = ""; } } else I have a foreach loop which shows the breadcrumb display. But it's stopped working. For some reason the links are no longer links. They are just echoed on screen with no <a> tags. setting up array: $crumb_query = mysqli_query($link, "SELECT f.forum_id, f.forum_cat_id, f.forum_name, c.cat_id, c.cat_name FROM ".TBL_PREFIX."forums as f LEFT JOIN ".TBL_PREFIX."categories as c ON c.cat_id = f.forum_cat_id WHERE f.forum_id = '$forum_id' ") or die(mysqli_error($link)); $crumb_info = mysqli_fetch_array($crumb_query, MYSQLI_ASSOC); $crumbs = array("index.php" => "Board Index", "./view_category.php?cid={$crumb_info['cat_id']}" => $crumb_info['cat_name'], "./view_topics.php?fid=$forum_id" => $crumb_info['forum_name']); echo build_crumbs($crumbs); the function: function build_crumbs($crumbs) { foreach($crumbs as $key => $value) { $crumb_display = "<a href=\"{$key}\">{$value}</a>"; $crumb_display = implode(" - ", $crumbs); } return $crumb_display; } can anyone see where im going wrong? what im trying to do is echo all of the results from the database query but add bold to results with a pid of 0. here is my code: $list = ''; $query = $link->query("SELECT * FROM ".TBL_PREFIX."forums ORDER BY f_lid ASC"); $result = $query->fetchAll(); foreach($result as $key => $val) { if($result[$key]['f_pid'] == 0) { $list .= '<b>'.$result[$key]['f_name'].'</b><br />'; } $list .= $result[$key]['f_name'].'<br />'; } echo $list; this works fine but the ones with a pid of 0 are displayed twice. once as bold and then once normal like so: General General New Features Testing Testing Sandbox Bugs my question is how to prevent this. For some reason I'm getting an invalid argument supplied for foreach error and I'm not sure why. Code: [Select] <?php // Include the database page require ('../inc/dbconfig.php'); if (isset($_POST['edit_event_lineup'])) { $event_items = $_POST['event_items']; $event_id = (int)$_POST['event_id']; foreach ($event_items as $items) { print_r($items); $segment_writer_id = (int)$_POST['segment_writer_id']; $introduction = mysqli_real_escape_string($dbc, $_POST['introduction']); $conclusion = mysqli_real_escape_string($dbc, $_POST['conclusion']); $segment_type = mysqli_real_escape_string($dbc, $_POST['segment_type']); $match_number = (int)$_POST['match_number']; $segment_number = (int)$_POST['segment_number']; $match_type_id = (int)$_POST['match_type_id']; $segment_title = mysqli_real_escape_string($dbc, $_POST['segment_title']); $match_type_id = mysqli_real_escape_string($dbc, $_POST['match_type_id']); $titles_id_list = mysqli_real_escape_string($dbc, $_POST['titles_id_list']); $stipulations_id_list = mysqli_real_escape_string($dbc, $_POST['stipulations_id_list']); $characters_id_list = mysqli_real_escape_string($dbc, $_POST['character_id_list']); $preview = mysqli_real_escape_string($dbc, $_POST['preview']); } $query = "INSERT INTO `event_segments` (event_id, segment_writer_id, segment_type, sort_order_preview, segment_title, preview, is_submitted_yes_or_no_id) VALUES ('".$event_id."', '".$match_writer_id."', '".$segment_type."' ,'".$sort_order_preview."','".$segment_title."','".$preview."',2)"; mysqli_query($dbc, $query); } ?> I am working on a photo gallery script in which I need to show 9 images at a time. Here is my script so far Code: [Select] <?php foreach($pictures->result() as $p): ?> <?php for($i = 1; $i <= 9; $i++) { ?> <div class="item"> <ul> <li><a href="images/gallery/<?=$p->category;?>/<?=$p->photo_name;?>" rel="example1" ><img src="images/gallery/<?=$p->category;?>/thumb_<?=$p->photo_name;?>" alt="#" /></a></li> </ul> </div><!-- end item --> <?php } ?> <?php endforeach; ?> At the moment the script is showing one image at a time 9 times and for every entry in my database. I have been battling this for a little while now. Thanks in advance for all of your help! |