...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
April 15, 2012

php arrays sorting contained values

Question by enrico

Ok, first of all, I’m not even sure the title is right, if so, I’m sorry.

I have this loop here which is the result of a MongoDB query:

foreach($cursor as $obj) {
   $monster = $obj["type"];
   $strenght = $obj["strenght"];
   $obj["value"] = rand(5, 15);
}

now, I have put rand there to signify that value changes for each iteration. Now i want that this array, when is printed, is ordered by that $obj["value"], and be able to chose if ascending or descending.


ok, I have tried this

foreach($cursor as $obj) {
   $type = $obj["monster"];
   $strenght = $obj["strenght"];
   $obj["value"] = rand(5, 15);

   $newarr[] = $obj;
}

    usort($newarr, "cmp");
    function cmp($a, $b)
    { return $b['value'] < $a['value']; }

    foreach ($newarr as $obj)
    {
        echo $obj['value'] . $obj['type'] . "<br/>";
    }

As I expected, the

 $obj["value"] = rand(5, 15);

does not get lost at every iteration in fact, the $newarr contains that value, the problem is that it does not sort them at all. The items are printed in the same order as they were put inside the array. Any help?

Thanks

Answer by thecodeparadox

function mysort ($arr,$d='asc') { 
        global $dir; 
        $dir = $d; 
        uasort($arr, 'cmp'); 
        return ($arr); 
    } 
    function cmp ($a, $b) {
        global $dir;
        if($a['value'] == $b['value']) return 0;
        else  {
            if(strtolower($dir) == 'asc')
                return ($a['value'] > $b['value']) ? 1 : -1;
            else if(strtolower($dir) == 'disc')
                return ($a['value'] > $b['value']) ? -1 : 1;

        }
    } 
    print_r(mysort($obj, 'disc'));

ACCORDING TO YOUR UPDATE

try this cmp()

function cmp($a, $b) {
    if($a['value'] == $b['value']) return 0;
    return $a['value'] > $b['value'] ? 1 : -1;
}

Answer by Starx

First of all, by doing $obj["value"] = rand(..) you are assigning same array variable with different values multiple times. By the end of the loop, the variable will only contain one value.

You probably were trying to do this

$obj["value"][] = rand(5, 15); //This adds a new random item to the array contained in $obj['value'] each time

When you have an array items, you can sort them by using sort()[ascending] function rsort()[Descending[

$sorted = sort($obj["value"]);
print_r($sorted);
Read more

CSS JS Display none alter div

Question by Michael

I have a one pager. And in that one pager, I have an item that is set as display:none (fixed side nav in a div).

Can I have it show when scrolling to a certain div?

So it starts out in the code but not displayed, and then when the user scrolls to #about can the side nav show up?

Answer by Parker

Essentially you will need to check if the user has scrolled to or beyond the div id of about.
First you will need to establish the current Y value of the div.

//cache about div
var about = $('#about');
//this caches the about div position on window load
var aboutPosition = about.position();

Next you will need to determine how far the the user has scrolled. The best way I have determined to accomplish this is with a timer. You could use the scoll event but its far too taxing on the user browser and a timer will be for the most part indistinguishable.

//generic timer set to repeat every 10 mili(very fast) 
//with a callback to execute the logic
var checkScrollPos = window.setInterval("scrollTopLogic()",10);

function scrollTopLogic(){
    //if about y position is greater than or equal to the 
    //current window scroll position do something
    if(aboutPosition.y >= $(window).scrollTop()){
        $('nav').show();
        //remove timer since it is no longer needed
        window.clearInterval(checkScrollPos);
    }
}

Answer by Starx

You can catch the scroll event of the div and show the element like this

$("#div").scroll(function() {
   $("#item").show();
});
Read more

append to div one time

Question by Mr. 1.0

I am revisiting this code I made a year ago with the help of another person. Unfortunately I don’t have contact with them anymore to get more help. Basically It dynamically adds classs to the tb and b nodes of a document coming from namesToChange. Now what I am trying to do is append some text to the div with class dtxt node but still use this code below. I am using the code $('td.pn_adm_jeff').children('div.dtxt').append('zzz'); and it works but it constantly appends more than once as seen in the photo below. How do I go about making it add once and stop?

Photo
http://img6.imageshack.us/img6/5392/7c23ddb145954aefadb1b9f.png

Code

   function customizefields(a) {
        $('td b').each(function () {
            name = $(this).text();
            if (name.indexOf(" ") != -1) {
                name = name.substring(0, name.indexOf(" "))
            }
            if (a[name]) {
                this.className = a[name].class;
                this.parentNode.className = a[name].img
            }
        })
        $('td.pn_adm_jeff').children('div.dtxt').append('zzz');
    }

    var namesToChange = {
        'Jeff'    :{'class':'pn_adm','img':'pn_adm_jeff'}
    };

    setInterval(function () {
        customizefields(namesToChange)
    }, 1000);

Update

var needsUpdate = true;

function customizefields(a) {
    $('td b').each(function () {
        name = $(this).text();
        if (name.indexOf(" ") != -1) {
            name = name.substring(0, name.indexOf(" "));
        }
        if (a[name]) {
            this.className = a[name].class;
            this.parentNode.className = a[name].img;
        }
    });
    if (needsUpdate) {
        $('td.pn_adm_jeff').children('div.dtxt').append('testing');
        needsUpdate = false;
    }
}

var namesToChange = {
    'jeff'    :{'class':'pn_adm','img':'pn_adm_jeff'};
};

setTimeout(function () {
    customizefields(namesToChange);
}, 1000);

Answer by Ozzy

use setTimeout rather than setInterval (interval is for repeating a timer task, timeout is a single timer task)

To prevent a certain task from occuring more than once in a repeated task, there is a simple fix.

// global variable
var needsUpdate = true;

// now in the timer task
if (needsUpdate) {
    $('td.pn_adm_jeff').children('div.dtxt').append('zzz');
    needsUpdate = false;
}

Does that work for you?

Answer by Starx

Define a global variable to hold the input flag

var appended = false;

function appendthestring() {
   if(!appended) $('td.pn_adm_jeff').children('div.dtxt').append('zzz');
   appended = true; 
}
Read more
April 14, 2012

How to set cursor at the end in a TEXTAREA? (by not using jQuery)

Question by Brian Hawk

Is there a way to set the cursor at the end in a TEXTAREA tag? I’m using Firefox 3.6 and I don’t need it to work in IE or Chrome. JavaScript is ok but it seems all the related answers in here use onfocus() event, which seems to be useless because when user clicks on anywhere within textarea, Firefox sets cursor position to there. I have a long text to display in a textarea so that it displays the last portion (making it easier to add something at the end).

Answer by Starx

Here is a function for that

function moveCaretToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

[Demo][Source]

Read more

Java string interpreted wrongly in SQL

Question by Shweta B. Patil

There is an string[] likely;
This array stores the name of column of database table dynamically while runtime.And the program understand the size of the likely in runtime.
Now to put this in sql query .I use a for loop for concatanation of string

for(int k=0;k<likely.length;k++)
    {
        temp1=""+likely["+k+"]+"='Likely' AND ";
        temp=temp.concat(temp1);                
    }

if the size is 3 the final temp will look like

temp = " "+likely[0]+"='Likely' AND "+
    likely[1]+"='Likely' AND "+
    likely[2]+"='Likely' AND "

Now i formulate sql query as

sql ="SELECT * FROM PUNE WHERE"+temp+"Arts_And_Museum='Yes'";

But during the

ps = con.prepareStatement(sql);

this statement is compiled like

SELECT * FROM PUNE 
WHERE [+likely[0]+]='Likely' 
AND [+likely[1]+]='Likely' 
AND [+likely[2]+]='Likely' AND Arts_And_Museum='Yes'

After deep investigation ,I came to conclusion that it interprets ” as [ or ] alternately..

As a result i get an error
How should i solve this problem?

I run a for loop and prepare a string
I am trying to write a sql syntax

Answer by Starx

The symbol is used for escaping. On doing this, you are escaping all the front characters.

Whenever you are asking for an item in array you can access it using likely[k] no need for likey["k"]

Here is how you should do it.

temp1="\"+likely[k]+"\='Likely' AND ";
Read more

Why is my array.length returning such a high number?

Question by Trey

For some reason I can push JSON objects to my array “list”, but when I call its .length, it seems that I’m getting the number of characters rather than number of items.

UPDATE: See answers for solution. My script wasn’t returning characters, it was looping through exponentially.

$.getJSON('[omitted].php?callback=?',function(d,item){
    var list = []
    alert('Length: '+d.length) // d consists of 271 JSON objects, d.length = 271
    for (i=0;i<d.length;i++){
        $.each(d,function(){ // for each JSON object we add...
            list.push({'name':this.name,'href':this.href,'img':this.img})
        })
        if (i==d.length){
        alert('Completed - Length: '+list.length) // list.length = 44711. Why?
        }
    }
})

Note that when I use alert(list) I see:

[object,Object][object,Object][object,Object] ...

Rather than an array:

[[object,Object][object,Object][object,Object] ... ]

Answer by am not i am

I believe this…

$.each(d,function(){

should be this…

$.each(d[i],function(){

Otherwise you’re looping over the same d structure once for every item in d.

Answer by Starx

Lets see, the basic structure of a each statement

$.each(mixedVar, function(index, item) {
     //Here index, is not an array but singular item's index, so whenever
     // index.length will be applied it will be taken as a variables, that a list/collection/array
});

In the same way, your d is also returning a item’s index, which is a mixed variable, neither a list nor an array.

Read more

on click show div getting error

Question by user1160126

am very sorry for this new bie question, when i click on the lick the div should open when i click again it should close the div..please help me on this

<html>
    <head>
        <script type="text/javascript">
        var bool = 0;
            function showDiv(){
                if(bool==1){
                    bool=0;
                    document.getElementById(show).style.visibility = "hidden";
                }else if(bool==0){
                    bool=1;
                    document.getElementById(show).style.visibility = "visible";
                }
            }
        </script>
    </head>
    <body>
     <input type="button" value="click" onclick="showDiv();" />

        <div="show">
            <p>it is okay it is okay it is okay it is okay it is okay it is okay it is okay it is okay</p>
        </div>

    </body>
</html>

Answer by Gabe

You’re missing the quotes for the id argument for getElementById()

document.getElementById('show').style.visibility = "hidden";

Also the id attribute name is missing on the <div>

 <div="show">

Should be this:

<div id="show">

jsFiddle

Answer by Starx

When you are referring to

document.getElementById(show).style.visibility

The show refers to a variable, but you are trying to get it as a string, so you should get it quoted

document.getElementById('show').style.visibility
Read more

Data ordering issue in MYSQL

Question by Lewis Wheeler

got a small little problem I’m hoping someone can help me with.

I have the following dataset in MYSQL:

SELECT * FROM account;

pk  |  customer
1   |   1
2   |   0
3   |   1

I only need the customer column BUT I need it to be in the same order as above e.g.:

customer
1
0
1

However whenever I try and perform the following command, I get the following:

SELECT customer FROM account

customer
0
1
1

I have already tried the following with no luck:

SET @rownum=0;
SELECT @rownum:=@rownum+1 as rank, customer FROM account

rank |  customer
1    |   0
2    |   1
3    |   1

UPDATE: I forgot to add something important. I can’t rely on ordering by the primary key, mainly because the primary key could be a varchar and not integer in some circumstances.

I need the order in which the data was inserted in the database. When I do the same query returning varchar values it is in the correct order.

Any ideas?

Answer: SQL query no order by question

Answer by Evan Mulawski

SELECT customer FROM account ORDER BY pk ASC

Answer by Starx

You can define the order without selecting that column. So, use this

SELECT `customer` from `account` ORDER BY `pk` ASC
Read more

How do I get PDO to work on WAMP with PHP 5.4?

Question by JREAM

How do I get PDO to work on WAMP with PHP 5.4?
I have installed PHP 5.4 inside of WAMP (2.2d 32-bit). My PHP.ini file has it enabled (Inside of the 5.4 phpForApache.ini file). I downloaded the latest PHP 5.4 Thread Safe for windows.

But I can’t get the PDO extension to work. Here is my php info file:

Configure Command   cscript /nologo configure.js "--enable-snapshot-build" 
"--disable-isapi" "--enable-debug-pack" "--disable-nsapi" "--without-mssql" 
"--without-pdo-mssql" "--without-pi3web" 
"--with-pdo-oci=C:php-    sdkoracleinstantclient10sdk,shared" 
"--with-oci8=C:php-sdkoracleinstantclient10sdk,shared" "--with-oci8-11g=C:php-        sdkoracleinstantclient11sdk,shared" 
"--enable-object-out-dir=../obj/" "--enable-com-dotnet" 
"--with-mcrypt=static" "--disable-static-analyze" "--with-pgo"


PDO drivers no value

Answer by Starx

Article: http://www.bluefrog.ca/2012/03/adding-php-5-4-0-final-support-to-wampserver/

Though you’ll now have support for 5.4, you’ll be missing some fancy extensions and features that you may have gotten used to on other
versions of PHP. These may include:

Xdebug
APC
PDO drivers
Curl
etc…

I will suggest installing Apache 2, Mysql, PHP separately. And its working just fine.

Read more

'syntax error, unexpected T_CONSTANT_ENCAPSED_STRING' Adding google event tracking to button in WordPress Plugin

Question by siggy_lxvi

I’m attempting to add a google event tracking to a wordpress plugin. The code for the submit button in this plugin is:

{
        return "<input  type="submit" ".
                "name="".fm_form_submit_btn_name()."" ".
                "id="".fm_form_submit_btn_id()."" ".
                "class="submit" ".
                "value="".fm_form_submit_btn_text()."" ".
                "onclick="".fm_form_submit_btn_script()."" ".
                "  />n";
    }

I’m trying to add google analytics tracking code onclick=_gaq.push(['_trackEvent', 'Form', 'Submit', 'Apply']) to the above block, and eventually replace 'Apply' with fm_form_the_title() which returns the title of the form.

The problem: No matter what arrangement of quotes I use when inserting the tracking code block, I am faced with an error ‘syntax error, unexpected T_CONSTANT_ENCAPSED_STRING’ or ‘T_STRING’ which shuts down the entire site.

EDIT: The code block above works, and does not need simplifying, and is part of a much larger project. My question is how to add onclick=_gaq.push(['_trackEvent', 'Form', 'Submit', 'Apply']) and eventually replace 'Apply' with fm_form_the_title() and NOT break my website.

Answer by Starx

How about simplyfing this with

return '<input  type="submit" '.
'name="".fm_form_submit_btn_name()."" ".
'id="'.fm_form_submit_btn_id().'"'.
'class="submit"'.
'value="".fm_form_submit_btn_text().'"'.
'onclick="'.fm_form_submit_btn_script().'"'.
'  />n';
Read more
...

Please fill the form - I will response as fast as I can!