June 29, 2012

awkward duplication in 2d array php

Question by shanahobo86

I merged two arrays together that both contained a string(url) and int(score). the following is a sample of the outome. Whenever a string is duplicated, i need to remove that string and its corresponding int. For example, on the 4th line (www.thebeatles.com/ – 30) should be removed. The 5th and 6th lines should also be removed as they appear already with a different score.

http://www.thebeatles.com/ - 55
http://en.wikipedia.org/wiki/The_Beatles - 49
http://www.beatlesstory.com/ - 45
http://www.thebeatles.com/ - 30
http://en.wikipedia.org/wiki/The_Beatles - 28
http://www.beatlesstory.com/ - 26
http://www.beatlesagain.com/ - 24
http://www.thebeatlesrockband.com/ - 23
http://www.last.fm/music/The+Beatles - 22
http://itunes.apple.com/us/artist/the-beatles/id136975 - 20
http://www.youtube.com/watch?v=U6tV11acSRk - 18
http://blekko.com/ws/http://www.thebeatles.com/+/seo - 17
http://www.adriandenning.co.uk/beatles.html - 16
http://www.npr.org/artists/15229570/the-beatles - 15
http://mp3.com/artist/The%2BBeatles - 14
http://www.beatles.com/ - 13
http://www.youtube.com/watch?v=TU7JjJJZi1Q - 12
http://www.guardian.co.uk/music/thebeatles - 11
http://www.cirquedusoleil.com/en/shows/love/default.aspx - 9
http://www.recordingthebeatles.com/ - 7
http://www.beatlesbible.com/ - 5

I’m new to PHP and my best efforts to get array_unique() to work have failed. Really appreciate some help guys!

Answer by Sven

Here is a function that merges two arrays and discards any duplications, hopes it helps:

        function merge_links($arr_l, $arr_r) {
            $new_links = array();
            $links = array_merge($arr_l, $arr_r); //the big list with every links

            foreach($links as $link) {
                $found = false; //did we found a duplicate?

                //check if we already have it
                foreach($new_links as $new_link) {
                    if($new_link['url'] == $link['url']) {
                        $found = true;


                //not found, so insert it
                if(!$found) {
                    $new_links[] = $link;

            return $new_links;

        $arr1[0]['url'] = 'http://test.nl';
        $arr1[0]['score'] = 30;

        $arr1[1]['url'] = 'http://www.google.nl';
        $arr1[1]['score'] = 30;

        $arr2[0]['url'] = 'http://www.tres.nl';
        $arr2[0]['score'] = 30;

        $arr2[1]['url'] = 'http://test.nl';
        $arr2[1]['score'] = 30;

        print_r(merge_links($arr1, $arr2));

Answer by Starx

Well, even technically, those strings are not unique. i.e. They are completely different.

So, array_unique() will not give you the required output. One way of solving this issue is by defining a separate array and storing the URI and the number separately. A manageable form would be this.


    array("http://www.thebeatles.com", 55),
    array("http://www.thebeatles.com", 30)


The animate callback function called immediately

Question by Ajax3.14

I am using the below line to blink a block. It works but the callback function incre() is called immediately and does not wait till blinking is over.

I need to call incre() only after the animate function blinks 2 seconds. What am I missing?

block.attr({ opacity: 0.3 }).animate({ opacity: 1 }, 2000,incre());

Answer by Starx

For what you are attempting fadeTo() sounds like a good choice

block.fadeTo(2000, 0.3, function() {
    block.fadeTo(2000, 1);


However, the error in your codes are:

  • the () (Brackets after the callback function name) i.e. incre()
  • opacity is a CSS property not an attribute. so user .css() to manipulate them

The correct codes are:

   .css({ opacity: 0.3 })
   .animate({ opacity: 1 }, 2000, incre);

Working Demo

Confuse about javascript callback function

Question by hh54188

I write two function, which callback will be invoke by the fn:

var callback = function (num) {
        return num + 1;    
var fn = function (callback) {


the firebug tell me: number is not a function ,I know the callback is execute immediately, how can I let it execute in the fn return the num in the fn function, the fn function is only allow the callback parameter

Answer by Elias Van Ootegem

Your example is a not great, seeing as there is no actual need for a second function. But this is what I’d do all the same:

function makeCallback(num)
    return function()
        return num+1;

fn = function (callback)

Seeing that a callback is generally called in an object context (DOM elements, when an event is handled etc) You might want to call the callback function, you passed as an argument to be called in the objects’ context.

Closures are a bit daunting and hard to fathom at first, but there are some great videos with Douglas Crockford on youtube on the matter, that really explain their workings well

Answer by Starx

It is happening due the parameter naming. The way you are using the parameters, makes a call to function called 6() which ends up being incorrect.

So, Use the following (IMO, this is what you are attempting)

var callback = function (num) {
        return num + 1;    
var fn = function (num) {



And so far for the attempt of your to create a callback function. You are only missing a return statement in the function see the result.

var callback = function (num) {
        return function(){
                return num + 1;
var fn = function (callback) {
    return callback();



June 28, 2012

add data dynamically from JSON array to HTML table using JQuery

Question by nag

php file:

$sql=mysql_query("select first,last,email,city from userdata"); 

json output:


html code:


        $("#userdata tbody").html("");
                    var tblRow =
                    $(tblRow).appendTo("#userdata tbody");

i was displayed data from database using php in JSON format..i want to insert this data into table format in html page, i created table in html also..i tried using above script but it didn’t fetch any data..plz help me plz..

Answer by Starx

Your PHP is printing the array in an incremented format.

Make the following changes:


Next, there is no userdata in the output, so just use data.

php file cannot be fetched while running html file

Question by user1487874

I’ve a pre defined php file that has to be run when I run my HTML file on browser. It’s a part of learning AJAX from the book “Head Rush Ajax” and I downloaded those files from their website. But that PHP file’s not running and I can’t update my page. Please let me know if I’ve to install any other php related software to run the HTML file perfectly using PHP file.

Answer by Starx

PHP is a server side programming/scripting languages. Its needs a server capable of running PHP files. These servers include, Apacher web server, IIS and others too.

To test your application on your system during development, you can use many suites, like WAMPsever, LAMP Stack, XAMPP server, MAMP (Mac) and Local IIS too.

Why can't I animate a cloned element?

Question by markzzz

This is my code :

var newElement=$('.oggetto').eq(0).clone();
newElement.animate({ 'top': '2000px'}, 5000);

<div id="container">
    <div class="oggetto" style="left:0px;">&nbsp;</div>
    <div class="oggetto" style="left:50px;">&nbsp;</div>

but seems that “.oggetto” won’t to move after the clone().

In fact, if I just write :

$('.oggetto').eq(0).animate({ 'top': '2000px'}, 5000);

it works as well. Where am I wrong?

Answer by Starx

Because, first the cloned element have to inserted into the DOM and then should be animated.

var newElement=$('.oggetto').eq(0).clone();
$("#container").append(newElement); //add the element 

//Now animate
newElement.animate({ 'top': '2000px'}, 5000);


random number generation without duplicates

Question by Zendie

I have to show some banners in a webpage.The number of banners will be with in 10 (max 10). I can set the number of banners and each banner folder in database. Banner images are stored in separate server folders based on category. Banners are showing in columns.

My code is,
Here, long1,long2,…long10 are directory names from database

       $files = array();

               $openDir = opendir($dir);
                       while (false !== ($file = readdir($openDir)))
                               if ($file != "." && $file != "..")
                                       $files[] = $file;

mt_srand((double) microtime()*1000000);
 $randnum = mt_rand(0,(sizeof($files)-1));



 $img = $dir."/".$files[$randnum];

  <input type="image" class="advt_image" src="<?=$img;?>" alt="" name=""/>

ex: if there is 7 banner set in database, I have to show 7 banners from different or same folder.(some banners will be from same folder). I need to avoid the duplicate banners each time when I display a webpage.

I have assigned an array to store each random numbers. Do I need to change anything in code? any thought/idea?


Answer by restart

You can remove the image that is displayed from the $files array in the loop. this means you will have to check the length of the array in the loop as well. you could use array_diff for this.

$files = array(...); // this holds the files in the directory
$banners = array();  // this will hold the files to display
$count = 7;
for($i=0;$i<$count;$i++) {
    $c = mt_rand(0,count($files));
    $banners[] = $files[$c];
    $files = array_diff($files, array($files[$c]));

// now go ahead and display the $banners

Answer by Starx

A simple way to solve this problem would be create a array to hold the list of banner than before displaying them.

I didn’t read your code (Sorry), but here is a basic concept, with which this is possible.

$bannerList = array();

//Now, check if the list contains the banner before adding it
while($rows) { //your big list of banners

    if(!in_array($rows['bannerpath'])) {
        $bannerList[] = $rows['bannerpath'];


Why isn't this image showing?

Question by sab

I made a header image, but for some reason I can’t get it to appear from CSS.

Here’s a screenshot:
enter image description here

The header is in the same image directory as the index.html file. The background image is appearing, but not this header. I typed the header twice in the HTML as a div to test it in two different spots to see if it is working, but for some reason it is not showing up, I don’t get it lol.


#header {


<div id="header"></div>

Here’s an example of it. But I am not sure why it doesn’t work.

Answer by Rab Nawaz


You need provide height OR it will be dependent on the height of the inner content, which 0

 #header {

Answer by Starx

On seing the screenshot of the code. I found two problems.

  1. There is NO stylesheet attached on the first place
  2. header is used to identify two different elements. (Also mentioned by Blaster)

However, the main reason why it is not showing up in tinkerbin, is because the div neither contains any elements nor has a fixed dimensions. Check this update of your bin.

June 27, 2012

Adding an EJB to a web application in netbeans

Question by henry joseph

I was following a tutorial on how to create a web application in netbeans using Java EE 6. The tutor added a new bean by just right clicking on the project name->new->session bean. When I tried to follow the same instruction, I didn’t find the session bean when I went to new. I am using netbeans 6.9.1. Is there a way to add it ?


Answer by Starx

You can add, the session beans, by using project pane on the left side. (If this is not showing, Press Ctrl + 1 or go to windows -> select Projects)

Then to add the session beans

  • Right your project
  • Go to New
  • Find Session Beans, If not go to others
  • There find a category called “Enterprise JavaBeans”
  • Select Session Bean
  • Continue and complete the wizard.
June 26, 2012

How to restrict the div to margin right or left

Question by Rana Muhammad Usman

I have created a custom scroll. In which I am shifting the contents right and left by increasing or decreasing the margin. I want to restrict the div not to margin more when the last or first content is visible or you can say I want to make it like scroll. How I can restrict the div not to move anymore

$('#left').live('click' , function(){

$('#right').live('click' , function(){


JS Fiddle

Answer by Starx

Define and maximum limit for margin left or right, then use this value to compare before changing its position.

var maxMargin = 500, minMargin = 20;

$('#left').on('click' , function(){
    if($('#myDiv').css("marginLeft") > minMargin) {

$('#right').on('click' , function(){
    if($('#myDiv').css("marginLeft") < maxMargin) {

And use .on() rathan than .live(), as it has been deprecated.


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