...

Hi! I’m Starx

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

How to find the largest array from a multi dimensional array

Question by sunil kumar

Possible Duplicate:
Get the maximum value from an element in a multidimensional array?
find max() of specific multidimensional array value in php

Iam trying to find out the largest array from multi dimensional array.

Array
(
    [0] => Array
        (
            [comment] => ayya
            [commented_on] => 17/03/12
            [ckey] => 210029c5d80d8259d1599c9a
            [username] => pappa
            [up] => 2
            [down] => 0
            [vote] => 2
        )

    [1] => Array
        (
            [comment] => sdfsd
            [commented_on] => 17/03/12
            [ckey] => 08f6a34f96bdeef2903ddaf4
            [username] => jesse
            [up] => 2
            [down] => 0
            [vote] => 2
        )

    [2] => Array
        (
            [comment] => 159
            [commented_on] => 17/03/12
            [ckey] => 4da385124793336339268782
            [username] => jesse
            [up] => 2
            [down] => 0
            [vote] => 2
        )

    [3] => Array
        (
            [comment] => s
            [commented_on] => 17/03/12
            [ckey] => 299c77c52ee087e468e23e82
            [username] => jesse
            [up] => 2
            [down] => 0
            [vote] => 2
        )

    [4] => Array
        (
            [comment] => jh
            [commented_on] => 17/03/12
            [ckey] => 523c18820d8b8db827a240ad
            [username] => jesse
            [up] => 2
            [down] => 0
            [vote] => 2
        )

    [5] => Array
        (
            [comment] => jh
            [commented_on] => 17/03/12
            [ckey] => 9f824c11b0ecafcc38c09f4c
            [username] => jesse
            [up] => 1
            [down] => 1
            [vote] => 0
        )

    [6] => Array
        (
            [comment] => jh
            [commented_on] => 17/03/12
            [ckey] => c97e7ad4d205220c4b8b0332
            [username] => jesse
            [up] => 1
            [down] => 0
            [vote] => 1
        )

)

I would like to get the array having highest votes.
Highest means the array having highest vote

I have used the following code, but it is not working.

$large=array();
                    foreach($final2 as $f1){

                        foreach($final2 as $f2){

                            if($f1['vote']>$f2['vote'])
                                $large=$f1;

                        }

                    }

Answer by Starx

AFAIK array size is counted from the number of elements it has.

So may be this will help

$largeArraySize = 0;

foreach($arraylist as $array) {
   if(count($array) > $largeArraySize) {
     $largeArray = $array;
   }
}

// Hence $largeArray has the largest
print_r($largeArray);

Unless a large array come this code will take the first occurrence as the largest.

Read more

Jquery last selector solution

Question by Dejo Dekic

I have created this Fiddle with this code:

This is my problem I want to make same behavior by selecting last li (fifth) tag but not the fourth like in this example ,but I don’t know how to accomplish that:(

I hope that someone can help me with this…THX!!

$(document).ready(function() {

 $("button").click(function() {
    $('.active').removeClass('active').next('li').addClass('active')
      if ($('ul li:last').hasClass('active')) {
          $('ul li:last').removeClass('active')
          $('ul li:first').addClass('active')
      }

  });


});

Answer by Rob W

You should put part in an else block. Otherwise, both methods will run twice for the last list item, causing the last element to be “skipped”.

A better solution (demo: http://jsfiddle.net/9dF22/5/ ):

$(document).ready(function() {
    $("button").click(function() {
        var $li = $('ul li'),
            $active = $li.filter('.active:first'),
            $next = $active.next();
        $active.removeClass('active');
        if ($next.length) {               // length === 0 if there is no next one
            $next.addClass('active');
        } else {
            $li.first().addClass('active');
        }
    });
});

Demo: http://jsfiddle.net/9dF22/3/

$(document).ready(function() {
    $("button").click(function() {
        if ($('ul li:last').hasClass('active')) {
            $('ul li:last').removeClass('active')
            $('ul li:first').addClass('active')
        } else {
            $('.active').removeClass('active').next('li').addClass('active')
        }
    });
});

Answer by Starx

I got much better way to do this

$("button").click(function() {
    if($('.active').next('li').length != 0) {
        $('.active').removeClass('active').next('li').addClass('active')
    } else {
        $('.active').removeClass('active');   
        $("ul li").first().addClass('active');
    }      
});

Demo

Read more

Three table side by side overflow of div container?

Question by StevenChow

I’ve got a problem with my page’s layout.
I want to create 3 table and set them side by side, so I set float attribute of them is “left”, but the height of div container only fix with the 3rd table, two first table is overflow of the div. Please help me to fix it.
Here is my page

<body>

<div id="main">

    <table id="tbSA" class="tb">
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
    </table>

    <table id="tbShops" class="tb">
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
    </table>

    <table>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
        <tr><td>Code</td></tr>
    </table>

</div>
</body>​

and here is style

body {
    background-color: #5c87b2;
}
#main {
    margin: 10px 10px 15px 10px;
    background-color: #fff;
}

table, td {
  border: solid 1px #e8eef4;
}

.tb {
    float:left;
    margin-right:10px;
}​

Answer by Starx

This sort problem is because your first two table are floated. but the last one is not so the div will correctly resize to it to wrap the third table.

But it order to make the div wrap around the floated table too. You have to clear the floats.

There are many ways to solve this:

  1. The safest way is to use, a clearing div just before closing the parent div [Demo]

    <div style="clear:both"></div>
    
  2. Old popular way is to give overflow:hidden which will force the div to wrap around all the elements. This is what other answers are focused out [Demo]

  3. The third way is to use a .clearfix class and is the most popular way nowadays. [Demo]

    .clearfix:after {
        content: ".";
        display: block;
        clear: both;
        visibility: hidden;
        line-height: 0;
        height: 0;
    }
    
    html[xmlns] .clearfix {
        display: block;
    }
    
    * html .clearfix {
        height: 1%;
    }
    
Read more
March 16, 2012

Fixing vs Hiding "Undefined Variable" Errors in PHP

Question by Chords

Depending on which error reporting I set, my web app either works or displays a ton of errors. I was under the impression I didn’t need to initiate variables in PHP but setting the second error reporting seems to require it. What is going here? Should I go through and initiate all my variables?

error_reporting(E_ALL ^ E_NOTICE);

error_reporting(E_ALL | E_STRICT);

Answer by todofixthis

You are asking about whether to suppress the warning for uninitialized variables, but the code you are posting suppresses ALL E_NOTICE warnings. This is not quite the same thing, but it’s as close as you can get directly to what you’re asking; there is no way to suppress only uninitialized variable notices.

In a way, notices are possibly the most important warning/error messages of all because they point out potential logic errors, which are among the most difficult to identify and fix.

Given your options:

  1. Suppress ALL E_NOTICE warnings.
  2. Fix all uninitialized variables in your code.

I would recommend going with #2. It’s more work upfront, but a well-timed E_NOTICE might just save you a whole mess of trouble one day.

Answer by Starx

You will receive a notice error, if you reference an identifier before they were initialised.

For example:

echo $variable; // is referencing to $variable which is not set before
echo $arrayname['indexname'] // it is also referencing to indexname item of array,
// if not found it will index another notice error

So, make sure you declare an identifier/variable before you reference it on our code, and you will be safe.

Read more

Retrieve PHP Variables with ajax load function

Question by mistertodd

I have an index.php with this code

<div id="example" class="functions"></div> 
<script type="text/javascript">
var ajax_load = "<img class='loading' src='ajax-loader.gif' alt='loading...' />";
var loadUrl = "checks/example.php";
$("#example").load(loadUrl);
</script>

and in the checks/example.php file

$masterurl = $_POST['domain'];
echo $masterurl;

First Problem: the example.php can´t retrieve the $_POST Request, because ajax is outputting it like html. I have looked for JSON solutions – but not found anything for my problem.

Second Problem: if the index.php outputs the value from example.php, how can I take the value and from the and handle the value as another php variable? like

$value = [value from <div id="example"></div>]

UPDATE: First Problem resolved

<div id="example" class="functions"></div> 
<script type="text/javascript">
var ajax_load = "<img class='loading' src='ajax-loader.gif' alt='loading...' />";
var loadUrl = "checks/example.php?domain=http://www.example.com";
$("#example").load(loadUrl);
</script>


$masterurl = $_GET['domain'];
echo $masterurl;

but how can I take the value $masterurl in the index.php for a variable on the index.php?

UPDATE 2:
checks/example.php sends the following value = 35234 this value will be displayed in this div

<div id="example">35234</div>

how can I use this value on the same page for

<?php
$newvalue = "35234" // value from div id example
?>

Answer by Starx

That is an incorrect way to do make an request. .load() will only update the div with the returned value from the path, but does not help to send any data to the target.

Make a valid post, or get, to request the page and update the <div> with the returned code

$.post("checks/example.php", {
   varname : 'val', //send the data to the page using this format
   varname2 : 'value2'
}, function(data) {
   // data will hold the output from the example.php

   $("#example").html(data); //update the div with the output
});
Read more

Hide <li> element when not fully visible

Question by JeroenVdb

Basic: I have an unordered list with many listitems (containing a picture and title). Not knowing how long the title will be I don’t know the hight of each listitem. To the left of this list is a big picture with title that “sets” the hight of my list (depending of the height en length of the title).

What I try to do: When the last listitem of my list can’t be fully displayed, hide the whole listitem.

Examples: http://d.pr/eAlK & http://d.pr/8MVO

In the second example the 4th article is hidden because it wouldn’t be fully visible.

Is this possible? I prefer I clean way that works crossbrowser if possible…

Answer by Starx

Basically the idea is to calculate all the height of child elements together and compare with maximum allowed height.

Using jQuery

var neededHeight = $("#lhscontainer").outerHeight(); //you can also use static value 
var totalChildHeight = 0;
$("ul").children("li").each(function() {
    totalChildHeight+= $(this).outerHeight(); //add up to the total height 
    if(totalChildHeight> neededHeight) {  //compare if the height limit was exceeded
       $(this).hide(); // if it did, hide the current element
       $(this).nextAll().hide(); //hide all other list also
       return false; // break the loop to stop the further iteration
    }
});
Read more

MySQL WHERE IN ()

Question by netcase

My query is:

SELECT * FROM table WHERE id IN (1,2,3,4);

I use it for usergroups and a user can be in more than one group. but it seems that when a record has multiple id like 1 and 3, mySQL does not return that row.
is there any way to get that row too?

Any help would be appreciated!

Answer by Starx

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET.
Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);
Read more

Rounded shape div

Question by Andrew

I have a post div which sits on top of a weird background, and as you can see in this screenshot http://i.stack.imgur.com/L5Qj0.png the text runs over the area I would want it to. I tried to use border-radius, but unfortunately that only modifies the look of the div, with the text still running over.

What I am trying to accomplish here is to create some sort of shape for the div’s top right corner, in which the text will sit. I’ve tried to use some weird padding but that didn’t do the trick either. Any ideas would be much appreciated.

Answer by Starx

This is bug, do not give a radius that is bigger than the half of the container’s height. Only till this, it is efficient enough.

However, as an alternative take a look into this CSS Text Wrapper, this is exactly what you want.

Read more

Jquery datepicker date format

Question by Dale

How do I get my date to display like this: “yy-mm-dd” inside my date input textbox after I have selected a date?

Information is reading from a database.
So I need it saved in a database again.

JavaScript:

<script>
  $(document).ready(function() {
  $("#from").datepicker();
});
</script>

Html code:

<div class="field">
        <label>Date</label>
       <input type="text" name="date" value="<?php value('date'); ?>" id="from" />   
        <?php if(isset($errors['date'])) { ?>
        <div class="error"><?php echo $errors['date']; ?></div>
        <?php } ?>
 </div>

Things that I have tried:

http://docs.jquery.com/UI/Datepicker#option-dateFormat

http://docs.jquery.com/UI/Datepicker/formatDate

jQuery UI DatePicker – Date Format

jquery ui datepicker date format

Answer by Starx

Define the format during initialization

$("#from").datepicker({
    dateFormat: 'yy-mm-dd'
});

The value is updated as well. See an example.

Read more
...

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