Jump to content

requinix

Administrators
  • Posts

    15,055
  • Joined

  • Last visited

  • Days Won

    413

Community Answers

  1. requinix's post in object-to-array function works but throws php warning was marked as the answer   
    Really tired of people wanting arrays over objects...
     
    Look.

    $xml = new SimpleXMLElement("/path_to_file/file.xml", 0, true); // or simplexml_load_file if you insist foreach ($xml->row as $row) { echo "{$row->name} is {$row->age} years old<br>\n"; } See how easy that was? 
     
    As for the actual problem, try it out on a regular array (which has the same problem that objects do).

    echo "<pre>"; print_r(object2array(array("name" => "Happy", "age" => 20))); echo "</pre>";Now try to understand what it is doing:1. Is $object an array? Yes. foreach over it and call object2array on each member.
    2. Is $object["name"] an array? No. Call get_object_vars on it, see that the return value is no good, and call strval.
    3. Is $object["age"] an array? No. Call get_object_vars on it, see that the return value is no good, and call strval.
     
    It's assuming that every single value nested within the $object is either an object or array. And that's not necessarily - or even likely to be - true. It needs to check a) if $object is an array, or b) if $object is an object, or otherwise c) it's neither.
     
    But don't do that. Just use SimpleXML like it's supposed to be used. Objects aren't scary. They won't bite.
  2. requinix's post in Should duplicate values be removed from mysql IN clause? was marked as the answer   
    If the list has only constant values then it will be sorted and MySQL will do a binary search (->). That's one additional comparison every time you double the size of the list.
     
    While not a big difference, I'd remove them: one pass in PHP to remove vs. however-many additional comparisons in MySQL.
  3. requinix's post in Delete PHP Freaks Account was marked as the answer   
    As they said, we don't like to delete accounts around here. While you may no longer need your account, content you've contributed to the forum could be useful for other people browsing around or searching for a solution to their own problem.
     
    All you need to do is... just not use your account. No one will be offended.
  4. requinix's post in Using namespace with autoloader was marked as the answer   
    PHP needs fully-qualified names to determine what classes are. If you write just "PDO" then PHP will think you want the PDO class in the current namespace; if you're not in a namespace then great, otherwise it won't find the class (unless you happen to have one with that name). 
    Write \PDO.
     
    The class will be like "Path\To\Class"; the common answer is to convert backslashes to DIRECTORY_SEPARATORs and look for a matching filename.
    spl_autoload_register(function($classname) { $path = str_replace("\\", DIRECTORY_SEPARATOR, $classname); require "/path/to/classes/{$path}.php"; });But if that's all you need to do then you might as well use the built-in spl_autoload and put your /path/to/classes in the include path.
    spl_autoload_register(); // equivalent to spl_autoload_register("spl_autoload") Your autoloader ignores the entire namespace and only uses the class name. It will not be able to handle multiple classes with the same name but in different namespaces, like "Foo\Example" and "Bar\Example".
  5. requinix's post in syntax error, unexpected ')', expecting '(' was marked as the answer   
    If you want to make sure $argument is an array then you need

    public function authorize($ability, array $arguments)If you want the default value to be an empty array then you need
    public function authorize($ability, $arguments = array())If you want both - which I suspect is the case - then do both.
  6. requinix's post in Reverse Natural Sort issue was marked as the answer   
    Use usort() with strnatcmp() to implement your own sorting algorithm.

    usort($FIRST_NAT_SORT, function($a, $b) { $a1 = strtok($a, "-"); $a2 = strtok(""); $b1 = strtok($b, "-"); $b2 = strtok(""); return strnatcmp($a1, $b1) ?: -strnatcmp($a2, $b2); });[edit] It's been asked so I'll explain: 
    The function to usort() has to return 0 depending on how the two arguments ($a and $b) compare to each other - negative if $a $b. Fortunately that's exactly how strnatcmp() behaves too.
    return strnatcmp($a1, $b1) will handle sorting for just the parts before the hyphens, but if they're equal then you need to compare the parts after the hyphens. $x ?: $y is shorthand for $x ? $x : $y, so

    return strnatcmp($a1, $b1) ? strnatcmp($a1, $b1) : -strnatcmp($a2, $b2);(except the shorthand will only evaluate the first strnatcmp() once) 
    Since strnatcmp() returns 0 if the two are equal and nonzero if not, the function will return that number if the two are not equal because it won't try to do the second comparison.
     
    If they are equal then the second strnatcmp() does get evaluated. It works the exact same way as the first one, except it has a minus sign to negate the return value. Thus the result is backwards: negative if $a2 > $b2 and positive if $a2 $b2. The effect is a descending sort on the values after the hyphens.
     
    To be absolutely explicit about everything you could write that line as

    $compare1 = strnatcmp($a1, $b1); if ($compare1 < 0) { // $a1 < $b1 return -1; } else if ($compare1 > 0) { // $a1 > $b1 return 1; } // $compare1 == 0 and $a1 == $b1 $compare2 = strnatcmp($a2, $b2); if ($compare2 < 0) { // $a2 < $b2 return 1; // opposite result } else if ($compare2 > 0) { // $a2 > $b2 return -1; // opposite result } else { return 0; }
  7. requinix's post in regex none or many ? was marked as the answer   
    There are too many things that are optional in that regex. Either you need to make some stuff required or you should combine some of them with alternation and make the whole set required.

    (first?)(second?)(third?) -> (?:first|second|third)If neither of those then we might have to rebuild the regex from scratch...
  8. requinix's post in Is it possible to do these things? was marked as the answer   
    I think Groot is trying to say he wants to make the page on the other site do something, such as open a popup window upon arrival.
     
    If that's the case then no, it is not possible. You cannot make someone else's site do something it wasn't designed to do.
  9. requinix's post in empty post was marked as the answer   
    A form field will be sent even if it is not visible to the user. Because you have the inputs named "link" you will always receive something like

    link=hariciLink&link=black&link=or
    link=dahiliLink&link=black&link=Örnek:%20http://www.websayfam.comThe hariciLink value overwrites the dahiliLink value because it is later in the form. 
    Easy solution: don't name everything "link". Very easy. Also a good idea.
     
    Otherwise you have to worry about enabling and disabling inputs so that only the right ones get submitted with the form.

    <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ if($(this).attr("value")=="hariciLink"){ $(".box").not(".hariciLink").hide(); $(".hariciLink").fadeIn(300); } if($(this).attr("value")=="dahiliLink"){ $(".box").not(".dahiliLink").hide(); $(".dahiliLink").fadeIn(300); } }); }); </script>That code is what you use to show and hide the different link inputs. To make it enable/disable you can
    <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ if($(this).attr("value")=="hariciLink"){ $(".box").not(".hariciLink").hide(); $(".box").not(".hariciLink").find(":input").prop("disabled", true); $(".hariciLink :input").prop("disabled", false); $(".hariciLink").fadeIn(300); } if($(this).attr("value")=="dahiliLink"){ $(".box").not(".dahiliLink").hide(); $(".box").not(".dahiliLink").find(":input").prop("disabled", true); $(".dahiliLink :input").prop("disabled", false); $(".dahiliLink").fadeIn(300); } }); }); </script>or simply
    <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ $(".box").not("." + this.value) .hide() .find(":input").prop("disabled", true) ; $("." + this.value + " :input").prop("disabled", false) $("." + this.value).fadeIn(300); }); }); </script>Keep in mind that enabling/disabling the inputs comes with a visual change (stuff turns gray) so you should enable inputs before showing them and disable inputs after hiding them; .hide() is instant but if you changed to .fadeOut() then you'd have to disable after the fade out animation finished.
  10. requinix's post in struggling to nail this was marked as the answer   
    But what about a case like

    /search/xbox[/category/:category[/subcategory/:subcategory]]This becomes a problem of balanced brackets - simply checking for [] on either side isn't enough. 
    Two suggestions for how to handle this:
    a) Don't allow optional variables and force the user to make additional routes. I've done this and it helps if you can give the user a way to configure routing in a recursive way, like

    <route path="/search/xbox"> route information here... <route path="/category/:category"> additional overriding information here... </route> </route>The routing system matches as much as it can, gathers all the information along the way, and decides what to do. You could also support
    <route path="/search"> route information... <route path="/xbox"> route information... <route path="/category/:category"> route information... </route> </route> </route>where the route information gathered for just "/search" isn't enough to serve a page and thus results in some 404-type behavior. 
    b) Use regular expressions to turn the route pattern into another regular expression. I've done this one too. With your simple example you could have something like

    $route = "/search/xbox[/category/:category]"; // escape any regex metacharacters already present $regex = preg_quote($route, '#'); // if using # as the pattern delimiters // note that it will escape any of . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - // or you can make this much simpler by not escaping characters and trusting the user to write mostly-regex-safe patterns // transform escaped brackets $regex = preg_replace('/\\\\\[/', '(?:', $regex); $regex = preg_replace('/\\\\\]/', ')?', $regex); // transform variables $regex = preg_replace('/\\\\\w+)/', '(?P<$1>[^/]+)', $regex); // replace [^/]+ with whatever you think matches a variable var_dump($regex); // "/search/xbox(?:/category/(?P<category>[^/]+))?"then
    if (preg_match('#^' . $regex . '$#', $url, $matches)) {gives you stuff like
    Array ( [0] => /search/xbox ) Array ( [0] => /search/xbox/category/consoles [category] => consoles [1] => consoles )The route gets [0] for the full match, and both named (useful) and numeric (useless) captures matching the assorted variables (if present). 
     
     
    Why did I just say all that? Because at 4:30am I'm not seeing a "nice" way of solving your particular problem of dealing with the []s.
  11. requinix's post in INSERT INTO HELP was marked as the answer   
    If you use mysql_error() to get the error message then it will hopefully clue you into those trailing commas.
     
    Also, the mysql extension is really old and it's bad and you need to move to PDO or mysqli instead. Learn about them now and start using them before you write too much code and make it difficult to fix later.
    You also need to learn about prepared statements because any naive hacker could break that code and make Bad Things happen to your site. PDO and mysqli both support prepared statements.
  12. requinix's post in How to simplify this JavaScript into something useable? was marked as the answer   
    Remember this?

    expected profit = bet * odds of losing / odds of winningLet's revise that a little bit to be more clear what it means. (It was late night when I wrote that and it made sense to me.)
    expected profit = bet * (odds of not winning - house edge) / odds of winningIf you predict 88 then your high roll must be within 89-99 to win. That's 99 - 88 = 11 out of 100 (or 100% - 88% - 1% = 11%). Not winning would thus be 89%. If you wager 5 and the house gets 0.96% then
    expected profit = 5 * (89 - 0.96) / 11 = 40.01818Look familiar? I imagine that logic is buried somewhere in the Javascript, though it looks like they're using an alternative form that calculates gross and not net winnings. Same difference.
  13. requinix's post in Change date stored as epoch to datetime when altering table? was marked as the answer   
    I suspect doing that will try to interpret existing data as YYYYMMDDHHMMSS strings, not as Unix timestamps.
     
    Will definitely work: add the created_at column, UPDATE it using FROM_UNIXTIME(user_date), then drop user_date. Three statements.
  14. requinix's post in pattern help was marked as the answer   
    You aren't repeating that character set at the end.
     
    As for the format, [0] will always be the full match. Best you can get is "i" as [1] and the identifier as [2] by using what you have now with the PREG_SET_ORDER flag.
  15. requinix's post in how can a css button be used to send php post data if at all was marked as the answer   
    Plain HTML does not support submitting forms using links. You have two options:
     
    a) Use a form button ( or ) and style it like the way you want. It is possible and not much more work to do since you have the appearance already working for a link.
    b) Put an onclick handler on the link and cause it to submit the form. This isn't AJAX but it does require Javascript.
     
    The first option is much better than the second.
  16. requinix's post in If you don't specify a length for a data type/column, does that affect performance? was marked as the answer   
    Have you tried looking at the documentation?
     
    Dates and times don't even have lengths. The string values do, sure, but the data type itself doesn't.
    Lengths only matter on field types that (can) have variable length data. Like strings and numbers: for VARCHARs it is the maximum character length stored, while for *INTs it is only the display width.
  17. requinix's post in Comparing Times was marked as the answer   
    You can compare
    a) A date/time formatted as Y-m-d or Y-m-d H:i:s or H:i:s. Anything else probably won't work. The rules are complicated (I'll explain if you want) so stick to just those three formats.
    b) Unix timestamps
    c) DateTime objects
  18. requinix's post in Updating an array held in a text file was marked as the answer   
    JSON would be really nice.
     

    { "subTitle": "Welcome to the Site" } // read $site = json_decode(file_get_contents("/path/to/file.json"), true); // write file_put_contents("/path/to/file.json", json_encode($site)); You do lose some of the PHP caching, though. To write out the array to a PHP file, use var_export.
  19. requinix's post in different div is result has value more than 1 was marked as the answer   
    counter = 1
    for each image {
    if counter = 1 {
    output div code with inline-block
    } else {
    output plain div code
    }
    output image code
    output closing div

    counter++
    }
  20. requinix's post in Showing a thank you message after form submit was marked as the answer   
    The page is being refreshed because of that location.reload(), so if you don't want that to happen then don't put that code in there.
     
    Is the .alert-success (which you should probably put an ID on rather than relying on just the class name) visible? As in it doesn't have a display:none or something? If it is, and probably should be, then you need to .show() it too.
  21. requinix's post in parsing XML was marked as the answer   
    Inside the foreach loop you have to use $entry. $xml->entry-> will only get you stuff from the first .
  22. requinix's post in json decode with foreach was marked as the answer   
    foreach ($output['data'] as $item){
  23. requinix's post in Help with json to javascript was marked as the answer   
    No, you cannot return from the function. Just like you cannot use return in your original code.
    Unfortunately I can't find anything good that explains how AJAX works and what you can and cannot do with it. Unfortunate because I wanted to give you something to read (preferably something that would take more than a couple minutes) before you touched any more code.
     
    The callback function has to do a thing. It cannot return a thing. Use it to perform an action. Put the code performing an action inside the callback.
     
    1. Why are you even using AJAX for this? Do you expect the list of users to change while the page is still open? What was wrong with the json_encode() from earlier?
    2. The "callback function has to do a thing" approach will not work for that code. It's already within an event handler. Probably the most appropriate approach would be to set a variable (like but not quite how the other variables around lines 62+ are set) containing the list of users, and put that variable on line 197. But to do this best requires an answer to my first question.
  24. requinix's post in shorthand syntax help was marked as the answer   
    If I may translate that,

    If you mean the ternary operator ? : then the answer is,
    While possible, in this case you shouldn't. That's more appropriate if you have "if ($condition) $var = $value; else $var = $other_value;". Your if has two statements in that else so it's really just better to leave it as is. And this is coming from someone who generally does use shorthand.
  25. requinix's post in listing multiple arrays in order was marked as the answer   
    FYI, next time you post code, make sure you remove sensitive information like the appid you had in that URL.
     
    So that code makes more sense than the one earlier, and doesn't have as much that needs to change.
     
    You already have a loop that goes over all the locations, so do the work of determining the highest and lowest in there.
    Do you only care about the temperatures? You like you don't care where the temperatures are from - just what they are?

    <?php session_start(); include_once("cxn.inc"); $today = date("Y-m-d H:i:s"); $sql = "SELECT airports.Name,airports.Country FROM airports INNER JOIN rosters ON airports.IATA = rosters.Arr WHERE rosters.Code = '$code' AND rosters.SectorDate >= '$today'"; $result = mysqli_query($cxn,$sql) or die ($cxn->error); $coldest = $hottest = null; while($row=mysqli_fetch_assoc($result)) { $link = 'http://api.openweathermap.org/data/2.5/weather?q='.$row['Name'].','.$row['Country'].'&units=metric&mode=xml&appid=*'; /* WEATHER API */ $xml=simplexml_load_file("$link") or die ("Cannot create object."); $temp = (int)$xml->temperature['value']; // converting to int is important or you'll have a bunch of SimpleXMLElement objects if (is_null($coldest) || $temp < $coldest) { $coldest = $temp; } if (is_null($hottest) || $temp > $hottest) { $hottest = $temp; } } /// OUTPUT GOAL /// echo $coldest; echo '<br />'; echo $hottest; ?>
×
×
  • 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.