-
Posts
579 -
Joined
-
Last visited
Posts posted by Drongo_III
-
-
Hi Guys
Bit of an odd one. I've created a custom 500 error page and my hosting company has told me that they've made the necessary httpd.conf changes.
The thing is - how do you simulate a 500 server errror?
I've tried throwing an exception but this did nothing. I've also tried breaking a htaccess file but this doesnt display my custom page, which leads me to think that the configuration hasn't been setup properly. But as I'm not sure if this is a valid way to test it I thought I would get some advice.
Any helo would be appreciated!
Drongo
-
CaSe SeNsEtIvE
It would be funny if it wasn't so stupid lol... I will go now and lash myself in the garden to twenty minutes.
Sowwy!
-
Most likely you tried to call the getElementById before the page loads or before the element is on the page.
Perhaps you can point out where i'm doing it wrong? The below code doesn't work.
<!doctype html> <html> <head> <script type="text/javascript"> var mylink; function init(){ mylink = document.getElementById('link1'); alert(mylink.id); myLink.onclick = myFunc; } function myFunc(){ alert('click worked'); } </script> </head> <body onload="init();"> <a href="#" id="link1">Click me</a> </body> </html>
But if I replace that init function with a direct call to document.getElement (as per below) it works fine. So I am just trying to understand either what I am doing wrong or whether there is some fundamental precept of javascript i am missing (probable)...
function init(){ //mylink = document.getElementById('link1'); //alert(mylink.id); document.getElementById('link1').onclick = myFunc; }
And thanks for this mate but this is a different type of event registration. I am trying to work out why the traditional model doesnt seem to work for me
-
This should work.
window.document.querySelector("#elmId").addEventListener("click", myFunc, false);
Thanks for that. But it wasn;t so much that I couldnt get the event to work, or that I couldn't register the event in another way. What I was driving at is to try and understand why it works with document.getElementById but not when I simply use a resource (i.e. set a var with document.getElement... and then assign it to the event). Any ideas why that may be?
-
Hello, I have a script that displays data from a XML file into a table and it works great. What I want to do is try to set a background color to a table cell based on the report element it gets from the XML file. I have another script I have done this for and it works great. For some reason I can't seem to get it working with this script.
Here is a working page of what it should look like. If you look below the map the tables have different backgrounds depending on the report.
http://www.mesquiteweather.net/wxsvr.php
Here is the actual page I am trying to get it to work on and the code I am using below.
http://www.mesquiteweather.net/wxspotter.php
<?php ####################################################################################### # # SPOTTER NETWORK STORM REPORTS # version 1.00 # # This program is free and no license is required. # # # mesquiteweather.net # ####################################################################################### //// SETTINGS //// //// SETTINGS //// $bkgColor = '#d4d4d4'; // Background color Examples: "gray" "#CCC" "#CCCCCC" $bc = '#EEEEEE'; // Background color of table cells $dtColor = '#FFF'; // Date & time color Examples: "#FC0" "#FFCC00" "white" $width = '100%'; // Set the width of the report tables //// END OF SETTINGS //// ####################################################################################### ini_set('display_errors','1'); ## Start Configurable data ## //Set path to data file $data = "http://www.spotternetwork.org/data.php"; ## End Configurable data ## // overrides from the Carter Lake Settings.php file (if applicable) global $SITE; if(isset($SITE['cacheFileDir'])) {$cacheFileDir = $SITE['cacheFileDir']; } if (isset($SITE['imagesDir'])) {$imagesDir = $SITE['imagesDir'];} if(isset ($SITE['tz'])) {$ourTZ = $SITE['tz'];} if(!function_exists('date_default_timezone_set')) { putenv("TZ=" . $ourTZ); } else { date_default_timezone_set("$ourTZ"); } // get path info & protect for cross-site scripting vulnerability $sri = ($_SERVER['REQUEST_URI']) ? str_replace('#SA', '', htmlspecialchars(strip_tags($_SERVER['REQUEST_URI']))) : ''; // set borders $bbrdr = 'border-bottom:thin solid black'; // bottom $lbrdr = 'border-left:thin solid black'; // left $rbrdr = 'border-right:thin solid black'; // right $tbrdr = 'border-top:thin solid black'; // top $sbrdr = 'border-right:thin solid black; '. 'border-left:thin solid black'; // side //Define table to display after each storm report $afterTable = "<table style='margin-bottom: 5px;' border='0' cellpadding='0' cellspacing='0' width='100%'><tbody><tr><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td class='shadow-mid' width='100%'><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td></tr><tbody></table>\n"; // Let's assign the table some styles $noMessageStyle = "width:{$width}; text-align:center; margin:0px auto; background-color:{$bkgColor};"; $td1Style = "{$tbrdr};{$sbrdr}; padding:2px 0px 2px 6px; background-image:url({$imagesDir}headerbgd2.gif); color:{$dtColor};"; $td2Style = "{$sbrdr}; padding:6px 0px 0px 6px;"; $td3Style = "{$sbrdr}; line-height:5px;"; $td4Style = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px;"; //Set message to display if there were not report $noStormMessage .= "<table style='{$noMessageStyle}' cellpadding='0' cellspacing='0'>\n"; $noStormMessage .= "<tbody>\n"; $noStormMessage .= " <tr><td style='{$td1Style}'>LIVE STORM SPOTTER REPORTS</td></tr>\n"; $noStormMessage .= " <tr><td style='{$td4Style}'>There are currently no storm reports</td></tr>\n"; $noStormMessage .= "</tbody>\n"; $noStormMessage .= "</table>\n"; $noStormMessage .= $afterTable; $xml = simplexml_load_file($data); //Set initial output to false $tData = false; foreach($xml->report as $report) { $date = $report['stamp']; $time = strtotime($date.'UTC'); $dateInLocal = date("D g:i a", $time); $narrative = $report['narrative']; $loc = $report['city1']; $tz = $report['tz']; $stormType = 'Unknown'; foreach($report->attributes() as $typeKey => $id) { if($id == 1) { if(array_key_exists($typeKey, $stormTypesAry)) { $stormType = $stormTypesAry[$typeKey]; } break; } } $stormTypesAry = array( 'tornado' => 'Tornado', 'funnelcloud' => 'Funnel Cloud', 'wallcloud' => 'Wall Cloud', 'rotation' => 'Rotation', 'hail' => 'Hail', 'wind' => 'Wind', 'flood' => 'Flood', 'flashflood' => 'Flash Flood' ); $reportColor = ''; switch($stormTypesAry) { case 'Tornado': $reportColor = 'rgba(128, 128, 128, 0.4)'; break; case 'Funnel Cloud': $reportColor = 'rgba(255, 222, 173, 0.4)'; break; case 'Wall Cloud': $reportColor = 'rgba(255, 20, 147, 0.4)'; break; case 'Rotation': $reportColor = 'rgba(255, 228, 181, 0.4)'; break; case 'Hail': $reportColor = 'rgba(255, 255, 0, 0.4)'; break; case 'Wind': $reportColor = 'rgba(255, 0, 0, 0.4)'; break; case 'Flash Flood': $reportColor = 'rgba(255, 165, 0, 0.4)'; } // Set table style $tableStyle = "width: 100%; margin:0px auto; background-color:{$bkgColor};"; $td1Style = "{$tbrdr};{$sbrdr}; padding:2px 0px 2px 6px; background-image:url({$imagesDir}headerbgd2.gif); color:{$dtColor};"; $td2Style = "{$sbrdr}; padding:6px 0px 0px 6px; background-color:{$reportColor};"; $td3Style = "{$sbrdr}; line-height:5px; background-color:{$reportColor};"; $td4Style = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px; background-color:{$reportColor};"; // construct data for table display $tData .= "<table style='{$tableStyle}' cellpadding='0' cellspacing='0'>\n"; $tData .= "<tbody>\n"; $tData .= " <tr><td style='{$td1Style}'><b>{$stormType}</b></td></tr>\n"; $tData .= " <tr>\n"; $tData .= " <td style='{$td2Style}'>Reported: <b>{$dateInLocal}</b> - </b>Location: <b>{$loc}</b></td>\n"; $tData .= " </tr>\n"; $tData .= " <tr><td style='{$td3Style}'> </td></tr>\n"; $tData .= " <tr><td style='{$td4Style}'>Description: <b>{$narrative}</b></td></tr>\n"; $tData .= "</tbody>\n"; $tData .= "</table>\n"; $tData .= $afterTable; } //If no storms were in the source, set no storm message if(!$tData) { $tData = $noStormMessage; } echo $tData; ?>
It should take this code to assign the colors....
$stormTypesAry = array( 'tornado' => 'Tornado', 'funnelcloud' => 'Funnel Cloud', 'wallcloud' => 'Wall Cloud', 'rotation' => 'Rotation', 'hail' => 'Hail', 'wind' => 'Wind', 'flood' => 'Flood', 'flashflood' => 'Flash Flood' ); $reportColor = ''; switch($stormTypesAry) { case 'Tornado': $reportColor = 'rgba(128, 128, 128, 0.4)'; break; case 'Funnel Cloud': $reportColor = 'rgba(255, 222, 173, 0.4)'; break; case 'Wall Cloud': $reportColor = 'rgba(255, 20, 147, 0.4)'; break; case 'Rotation': $reportColor = 'rgba(255, 228, 181, 0.4)'; break; case 'Hail': $reportColor = 'rgba(255, 255, 0, 0.4)'; break; case 'Wind': $reportColor = 'rgba(255, 0, 0, 0.4)'; break; case 'Flash Flood': $reportColor = 'rgba(255, 165, 0, 0.4)'; }
Then assign the table color style like so...
$td4Style = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px; background-color:{$reportColor};";
What am I missing or overlooking?
-Thanks
I may stand corrected here but at least one issue is that you are trying to pass an entire array to your switch statement, which as far as I am aware isn't possible. A switch usually takes a single value to evaluate against.
So you might want to do a foreach statement and run the switch in a function that can be called on each iteration.
-
Hi Guys
I have been a jquery junky for a bit too long and neglected much of the raw javascript behind it...hence this simple question.
When I try to register an event in the format of :
element.onclick = funcName;
the only way I can get this to work is with:
document.getElementById('elementId').onclick = myFunc;
Whereas if I try and give this event a handle (below) it doesn't work at all and I get an 'undefined' error in console even though it plainly is defined. But surely these two statements amount to exactly the same thing?
var someElement = document.getElementById('elementId'); someElement.onclick = myFunc; // This doesn't work
So what am i missing?
Thanks,
Drongo
-
Could anyone help with this one please?
-
Hello
I have a quick question. I want to make a custom 500 error page. I understand this is achieved by tweaking httpd.conf file to direct to a specific file in the event of a 500 error.
What I want to know is if I make a html 500 error page should this be located on another server? The logic being that if the server can't render any of the normal pages on a site due to a 500 error why would it be able to render my customer 500 page. Does that make sense? And whats the best practice here?
Thanks,
Drongo
-
Worked it out now.
Seems you have to declare that the first array level is an array too:
var locObj = []; locObj[1] = []; locObj[1]['top'] = 'twinky' alert(locObj[1]['top']);
Just thought I would post back in case anyone else gets stuck on something similar.
Though why you can't just write it like php is hard to fathom - still that's javascript for ya!
-
Hi Guys
Super simple question. I want to create a multidimensional JS array where I can define the keys. Perhaps my mistake is using similar syntax to php but the following code throws an error in chrome console saying "Uncaught TypeError: Cannot set property 'top' of undefined "
Can anyone nudge me in the right direction on this?
var locObj = []; locObj[1]['top'] = 200; alert(locObj[1]['top']);
-
I am not entirely sure what this is called, but say for example you have some text on a site, and you want to edit it right there and then, and you just click on the text, and it changes to a text field and you edit the text, then onblur it updates the text with the new content form the text field.
What is this called, and what is the best and easiest method of doing it?
Best way to do it... There are lots of methods for achieving this but all depends on how complex you want to make it. If you need the fields to be draggable or sortable then you may opt for a different option but what follows is a simple example to highlight how easy it is.
Just as a quick illustration (and i am typing this directly in so sry if it doesn't work)
<form> Country: <input type="text" name="someField" value="WHATEVER" onblur="this.style.border='0px'; setAttribute('readonly','true')" onfocus="this.style.border='1px solid black'; removeAttribute('readonly','0')"> </form>
-
Hi, New to php here please help me out.
So I have been trying to use the mail function to send mail to me, but it's not working I know i changed the fakeemail@example.com to mine, but it's not working and I can't figure out why. Plus do you know how I can add the emailers name and his email sent additionally with the message to me. Thanks.
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST' ) { if (mail('fakeemail@example.com','New Website Message', $_POST['message'])) { $status = "Thank you for your message {$_POST['email']}"; } } ?> <html> <head> <title></title> <style> label {display: block;} form ul {margin: 0; padding: 0;} form li {list-style: none; margin-bottom: 20px;} </style> </head> <body> <h1>Contact Form</h1> <form action="" method="post"> <ul> <li> <label for="name">Name: </label> <input type="text" name="name" id="name"> </li> <li> <label for="email">Email: </label> <input type="text" name="email" id="email"> </li> <li> <label for="message">Your Message: </label><br /> <textarea name="message" id="message" cols="30" rows="10"></textarea> </li> <li> <input type="submit" value="Go!"> </li> </ul> </form> <?php if (isset($status)) echo $status; ?> </body> </html>
Your logic should look something like this:
if(isset($_POST['email'])) { $to = 'YourEmail@host.com'; $subject = 'Your Subject Line goes here'; $message = $_POST['message']; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Mail it mail($to, $subject, $message, $headers); }
You can add in additional headers etc. which is all explained here - http://php.net/manual/en/function.mail.php
But that should get you started. You probably want a better way of checking if the form has been submitted - i just used $_POST email for an example.
-
Hi, I'm trying to make a php register and login form but it seems almost impossible. I've got this far and it keeps returning a row error and I have no idea what that means or what would be causing it? It keeps returning the "elseif(!mysql_num_rows($r))" and I have no idea why it's doing that? Really need help on this one cause I've been stuck on this problem for around 1 month now and no one seems to know why it's doing this. Thanks.
LOGIN.PHP
<?php session_start(); include "dbConfig.php"; $errorMsg = ""; if ($_GET["op"] == "fail") { $errorMsg = "* You need to be logged in to access the members area!"; } if ($_SERVER['REQUEST_METHOD'] == "POST") { $username = trim($_POST["username"]); $password = trim($_POST["password"]); if (empty($username) || empty($password)) { $errorMsg = "* You need to provide a username & password."; } else { $usernameSQL = mysql_real_escape_string($username); $passwordSQL = crypt($password); $q = "SELECT * FROM Table1 WHERE username='$usernameSQL' AND password='$passwordSQL' LIMIT 1"; $r = mysql_query($q) or die("Error: " . mysql_error() . "<br>Query: " . $q); if(!$r) { $errorMsg = "* Wrong username or password."; } elseif(!mysql_num_rows($r)) { $errorMsg = "* Sorry, couldn't log you in. Wrong login information."; } else { $_SESSION["valid_id"] = $obj->id; $_SESSION["valid_user"] = $username; $_SESSION["valid_time"] = time(); header("Location: members.php"); exit(); } } } ?>
REGISTER.PHP
<?php include ("dbConfig.php"); if ($_SERVER['REQUEST_METHOD'] == "POST") { $usernameSQL = mysql_real_escape_string($_POST['username']); $emailSQL = mysql_real_escape_string($_POST['email']); $passwordSQL = mysql_real_escape_string($_POST['password']); $passwordSQL = crypt($password); $q = "INSERT INTO Table1(username, email, password)VALUES('$usernameSQL', '$emailSQL', '$passwordSQL')"; $r = mysql_query($q); header("Location: register.php?op=thanks"); exit(); } ?>
Wouldn't advise using mysql anymore - it's deprecated. Use MySQLI or PDO.
Have you tried some debugging. I would suggest some of the following:
- echo out the crypted password and username after you set them and manually compare them to what you have in your database
- try tweak your query so you are only selecting the username, then only selecting the password - this might give you some idea of what variable is failing to match
- echo out the crypted password and username after you set them and manually compare them to what you have in your database
-
Hi Guys
I need to setup a MySQL user account so I can connect (using PHP) both on the server where MySQL resides and remotely from another server (these are load balanced servers).
I read a MySQL article here: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html - this seems to suggest in order to do this I would need to setup two user accounts as follows:
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass'; GRANT ALL PRIVILEGES ON MyDB.sometable TO 'monty'@'localhost' CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
I am not overly familiar with creating users so apologies for the noob questions about to follow:
- Is it correct that I need to setup two users with the same username only one as localhost and one with wildcard to be able to use the database locally and remotely ?
- Rather than use a wildcard would it be more secure to use the remote server's IP - i.e. 'monty'@'SomeIPaddress'?
- Do I need to grant privileges on the second user - i.e. 'monty'@'%' . Or does this account inherit the same privileges from 'monty'@'localhost'?
I would obviously not grant all privileges either but the above is just for simplicity.
Is that all I need to do?
Thanks
Drongo
- Is it correct that I need to setup two users with the same username only one as localhost and one with wildcard to be able to use the database locally and remotely ?
-
Hi guys
I implemented the code above as per the solution given but I seem to have a strange issue.
when I set outlook 2007 to receive plain text email only and perform a test send outlook seems to ignore the plain text version in the email and simply defaults to a plain text version it seems to derive from the html version.
has anyone seen this happen before and is to the code or something to do with outlook?
-
Drongo,
Not a problem, glad I could help.
As for attachments I don't think multipart/related is what you're looking for. multipart/related as I understand it are for emails which include different sections to complete an email... Like inline images and things like that. Or at least that how I understood https://tools.ietf.org/html/rfc2387. I believe for things like attachments you'll want to use multipart/mixed.
Another thing you may want to consider is to use some prebuilt libraries. Might save you alot of greif as most of this kind of stuff has already been written and available for your use. I know things like Zend Framework have some built in email libraries that you can use, or another one that I've seen recomended quite a bit is PHPMailer. Might save you some headaches.
Westin
Ahh I see. I need to go do some reading me thinks! Heard of phpmailer but not used it - probably should check these out but I am the worst person for wanting to do it all myself to learn how it works ha! There's a control freak in all of us I guess
Anyway thank you very, very much for the help!
-
OK Folks:
I am totally starting fresh with learning PHP starting with my first program that simply says "Hello World"
So, I've been watching a really cool video on YouTube that has been showing me how to write PHP code and as with any programming language, the first thing you learn is how to print the words "Hellow World" in the browser.
Anyway, so I have the following program, written in NotePad++:
<?PHPprint "Hello World";?>But, when I tell NotePad++ to launch the code in Chrome, instead of showing me just the words Hello World, it displays the entire code I wrote on the page as:<?PHPprint "Hello World";?>This is NOT the desired result.Also, in NotePad++, I want to upload this file to my web site, I see where there is an upload button, but it is not enabled to allow me to upload this test program to my site.I'm stuck!!! Any suggestions ?Thanks,Steven SchuylerBerkeley, CAYou should probably download an ftp program such as filezilla to push files to your server - never used notepad++ for it but I wouldnt trust the results tbh.
Also, to my knowledge, you cannot execute php code without a server. If you want to run php code locally you'll need to download something like WAMP server (http://www.wampserver.com/en/) which you can install and run as a server on your computer. This will then let you execute your php scripts. WAMP is insanely easy to install.
Hope that helps!
-
Found a couple of problems..
First, you really want to change your mime type From multipart/related TO: multipart/alternative. As these are not "related" to each other.
Second... you need to get rid of the spacing and \n's from within the body. As you are in a quoted string the carrage returns and spacing will all be applyed in the message.
Here's a working example with these changes:
<?php $headers = "MIME-Version: 1.0\n"; $headers .= "Content-Type: multipart/alternative; boundary=\"boundaryMarker\"\n"; $headers .= "Content-Transfer-Encoding: 7bit\n"; $body = <<<MyEmailMessage --boundaryMarker Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit THIS IS PLAIN TEXT EMAIL --boundaryMarker Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit <h1>THIS IS HTML VERSION</h1> --boundaryMarker-- MyEmailMessage; $to = 'me@myemail.com'; $subject = 'This is a test message'; mail($to, $subject, $body, $headers);
Lachild thank you so much for your response. That fixed it all and now works perfectly. I'm now very happy
As you've highlighted the mime type to me the penny kind of drops. So I guess 'multipart/related' might be used for things like attachments?
Might it have something to do with the indenting, and copious amount of newlines, you've added to the mail..?
Unfortunately I do not have the time (nor the desire, to be honest) to read up on the RFC to verify this. That said, it is worth looking into, and you should definitely read the RFC.
Also, no need to use "\n" inside the string to add newlines. You're already doing that with the actual newlines.
Christian - thanks for the tip. To be honest I was just working from examples on php.net which isn't overly expansive but I guess I'm looking in the wrong place for descriptive info on this. I shall check out RFC article.
-
This is probably going to centre around two main functions.
Firstly file_get_contents (http://www.php.net/manual/en/function.file-get-contents.php) to grab the page data. You can enter a url as the file name.
Then you'll want to break out your regular expressions and use a function such as preg match (http://php.net/manual/en/function.preg-match.php). This returns an array of matches.
I'm brand new to PHP coding (but was a old-time VB coder). I figured out how to search a URL for a string. What I'm looking to figure out is two-fold:
1. I want search a specific site and grab some content there that's date-specific. That date is listed in the site's Title tag so the title tag will say something like "This weekend's stats for February 22-23, 2013 ---".
I can search for the title tag but how to I go about actually turning just the key piece I need into a string?
2. Also on this page I need to find roughly 80 pieces of data that will be all the same except for one unknown string in the middle of 80 TD/URL/name tags (movie titles). How do I get the 80 items into an array? I'm sure I'll use a FOR loop or WHILE loop but what's the code for this look like to get those lines into strings?
Thanks.
-
Hi Guys
I am trying to setup an email template that contains both a html and plain text version in one.
What follows is a simplified version but what I want to do is simply have both versions in an email template and then run a str_replace which will populate the template's place holders with the relevant data before sending - this is why I want everything in a single file. But before I get to that point I simply need to get the email working - however at present when I run the code below I just get blank output in the email body.
If anyone could propose a reason why this is happening it would be appreciated.
Incidentally I realise the mime boundary isn't ideal - this is just for testing.
<?php $headers = "MIME-Version: 1.0\n"; $headers .= "Content-Type: multipart/related; boundary=\"boundaryMarker\"\n"; $headers .= "Content-Transfer-Encoding: 7bit\n"; $body = " --boundaryMarker\n Content-Type: text/plain; charset=\"charset=us-ascii\" \n Content-Transfer-Encoding: 7bit\n\n THIS IS PLAIN TEXT EMAIL \n\n --boundaryMarker\n \n\n Content-Type: text/html; charset=ISO-8859-1\n Content-Transfer-Encoding: 7bit\n\n <h1>THIS IS HTML VERSION</h1> \n\n --boundaryMarker--\n "; $to = 'MyEmail@Myemail.com'; $subject = 'This is a test message'; mail($to, $subject, $body, $headers);
-
Setup a network drive and mount it on both servers. You can either do this through a third server just to store the images or use one of the existing ones as the base.
Hi Kick
Sorry it has taken a while to respond to this.
Lets assume that this isn't possible to setup - because I have very limited control over the hardware in this instance.
As a way of doing it via php would perhaps ftping the files via php's ftp functions be a possible solution? Any reasons you would advise not using this?
-
Thanks Jessica
You give me too much credit and I can't in fact see from the time stamps what the dates are... However you did give me cause to check what I was doing with the dates and it appears it wasn't the output that was the problem but there was some test code messing up the strtotime conversion earlier in the code. So thank you for prompting me to check that.
You can easily look at those timestamps and see that they are IN FACT in order.
1357....
13587...
13589...
1359....
13874...
13877...
So...the problem is clearly not in the code you've posted.
Edit: The last one in the list is:2013-12-22 19:50:33
and the first is:
2013-01-04 01:35:43
I think you need to refer to date() for the right formats to use for your human-readable date.
-
Hi Guys
Posted on here a few days ago about sorting a multi dimensional array based on date. I thought I had it working but now i realise it doesn't appear to be sorting correctly.
Essentially I have an array that is combined from feeds from twitter and facebook. I converted the dates using strtotime and the unsorted array looks like this:
print_r($socialMediaArray); ( [0] => Array ( [date] => 1359214851 [message] => some message [from] => twitter ) [1] => Array ( [date] => 1358991499 [message] => some message [from] => twitter ) [2] => Array ( [date] => 1358799273 [message] => some message [from] => twitter ) [3] => Array ( [date] => 1387741833 [message] => some message [from] => twitter ) [4] => Array ( [date] => 1387490401 [message] => some message [from] => twitter ) [5] => Array ( [date] => 1357263343 [message] => some message [from] => facebook ) )
I then ran the following code to try and sort on date order
function cmp ($a, $B) { return $a['date'] - $b['date']; } usort($socialMediaArray, "cmp"); // Sort the array by date order. echo "SORTED ARRAY <pre>"; print_r($socialMediaArray); SORTED ARRAY Array ( [0] => Array ( [date] => 1357263343 [message] => some message [from] => facebook ) [1] => Array ( [date] => 1358799273 [message] => some message [from] => twitter ) [2] => Array ( [date] => 1358991499 [message] => some message [from] => twitter ) [3] => Array ( [date] => 1359214851 [message] => some message [from] => twitter ) [4] => Array ( [date] => 1387490401 [message] => some message [from] => twitter ) [5] => Array ( [date] => 1387741833 [message] => some message [from] => twitter ) )
But when I then convert the dates back into something readable it becomes apparent that the dates haven't been sorted correctly as they come out as
Fri Jan 04 1:35:43
Mon Jan 21 20:14:33
Thu Jan 24 1:38:19
Sat Jan 26 15:40:51
Thu Dec 19 22:00:01
Thu Dec 19 22:00:01
I'm not overly familiar with using usort, hence why I posted here, so if someone could offer up a possible reason as to why this may be happening it would appreciated.
Many thanks,
Drongo
-
Thanks very much guys that worked a treat. I was getting massively confused because I thought I have to pass $a and $b and I couldnt quite see how I would make that dynamic - over complicating it clearly!
The usort() function passes $a and $b to the callback function where $a and $b are pairs of elements in the array.
If you convert your dates to timestamps then
usort($array, 'cmp'); function cmp ($a $b ) { return $a['date'] - $b['date']; }
Adding HTML code to a string in the appropriate place.
in PHP Coding Help
Posted · Edited by Drongo_III
This should do the job. I got this very nifty regex off someone on here.