Wednesday, May 20, 2015

PHP: Page pagination in array

Code snippet:
$page = !empty( $_GET['page'] ) ? (int) $_GET['page'] : 1;
$total = count( $yourDataArray ); //total items in array
$limit = 10; //per page    
$totalPages = ceil( $total/ $limit ); //calculate total pages
$page = max($page, 1); //get 1 page when $_GET['page'] <= 0
$page = min($page, $totalPages); //get last page when $_GET['page'] > $totalPages
$offset = ($page - 1) * $limit;
if( $offset < 0 ) $offset = 0;

$yourDataArray = array_slice( $yourDataArray, $offset, $limit );

echo 'Pages: ';
for($i = 1; $i <= $totalPages; $i++){
 
 if($i == $page){
  echo '<b>' . $i . '</b> ';
 }elseif($i != $page){
  echo '<a href="testpage.php?page=' . $i . '">' . $i . '</a> ';
 }
 
}
Output:
Pages: 1 2 3 4 

Refer: http://stackoverflow.com/questions/26451362/how-to-add-php-pagination-in-arrays

Tuesday, May 19, 2015

PHP: Group array to unique value

Existing array:
Array
(
    [0] => Array
        (
            [id] => 12
            [name] => John
            [description] => this is a description.
        )

    [1] => Array
        (
            [id] => 57
            [name] => John
            [description] => test description.
        )

    [2] => Array
        (
            [id] => 85
            [name] => Amy
            [description] => testing 123.
        )

)
Apply this:
$result = array();

foreach ($arr as $data) {

        $name = $data['name'];
        if (isset($result[$name])) {
                $result[$name][] = $data;
        } else {
                $result[$name] = array($data);
        }

}
Output:
Array
(
        [John] => Array
        (
                [0] => Array
                (
                        [id] => 12
                        [name] => John
                        [description] => this is a description.
                )

                [1] => Array
                (
                        [id] => 57
                        [name] => John
                        [description] => test description.
                )
        )
        [Amy] => Array
        (
                [0] => Array
                (
                        [id] => 85
                        [name] => Amy
                        [description] => testing 123.
                )
        )
)

Refer: http://stackoverflow.com/questions/12706359/php-array-group

Tuesday, March 4, 2014

PHP: Remove duplicate value in array

Basic array:

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

Output:
Array
(
    [a] => green
    [0] => red
    [1] => blue
)
Refer site: http://sg3.php.net/array_unique

Multi-dimensional array:
<?php
$date = array(
array('month' => 'Jan', 'year' => '2010'),
array('month' => 'Jan', 'year' => '2010'),
array('month' => 'Jan', 'year' => '2010'),
array('month' => 'Feb', 'year' => '2010'),
array('month' => 'Feb', 'year' => '2010'),
array('month' => 'Mar', 'year' => '2010'),
array('month' => 'Apr', 'year' => '2010'),
array('month' => 'Apr', 'year' => '2010')
);

print_r(super_unique($date,'month'));

function super_unique($array,$key) {

   $temp_array = array();

   foreach ($array as &$v) {

       if (!isset($temp_array[$v[$key]]))

       $temp_array[$v[$key]] =& $v;

   }

   $array = array_values($temp_array);

   return $array;
}
?>
Output:
Array
(
    [0] => Array
        (
            [month] => Jan
            [year] => 2010
        )

    [1] => Array
        (
            [month] => Feb
            [year] => 2010
        )

    [2] => Array
        (
            [month] => Mar
            [year] => 2010
        )

    [3] => Array
        (
            [month] => Apr
            [year] => 2010
        )

)
Refer site: http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php

Wednesday, February 19, 2014

Web Tools: Find Facebook ID

For integrations of certain Facebook social plugins, like the "Like" button and "Like box", and others, Facebook requires that you know your Facebook numeric user ID.



Refer site: http://findmyfacebookid.com/

Sunday, February 9, 2014

Modernizr plugin: Progress button

Modernizr is a JavaScript library that detects HTML5 and CSS3 features in the user's browser. (Browser doesn't support: IE8 and below.)



Refer site: http://tympanus.net/Development/ProgressButtonStyles/

Modernizr plugin: Fullscreen overlay effect

Modernizr is a JavaScript library that detects HTML5 and CSS3 features in the user's browser. (Browser doesn't support: IE8 and below.)



Refer site: http://tympanus.net/Development/FullscreenOverlayStyles/index.html

Tuesday, February 4, 2014

PHP: Get Url Components

Example 1: Code

<?php
$url = 'http://me:you@sub.site.org:29000/pear/validate.html?happy=me&sad=you#url';

$output = parse_url($url);
echo '<pre>' . print_r(parse_url($url), true) . '</pre>';
echo 'Path: '.$output['path'];
?>


Example 1: Output
Array
(
[scheme] => http
[host] => sub.site.org
[port] => 29000
[user] => me
[pass] => you
[path] => /pear/validate.html
[query] => happy=me&sad=you
[fragment] => url
)
Path: /pear/validate.html

Example 2:
To retrieve just a specific URL component as a string:
PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT

Code

<?php
$url = 'http://me:you@sub.site.org:29000/pear/validate.html?happy=me&sad=you#url';

echo parse_url($url, PHP_URL_PATH);
?>


Output

/pear/validate.html


Example 3: Code

<?php
function parseUrl ( $url )
{
$r = '!(?:(\w+)://)?(?:(\w+)\:(\w+)@)?([^/:]+)?';
$r .= '(?:\:(\d*))?([^#?]+)?(?:\?([^#]+))?(?:#(.+$))?!i';

preg_match ( $r, $url, $out );

return $out;
}
$output = parseUrl($url);
echo '<pre>' . print_r($output, true) . '</pre>';
echo 'Path: '.$output[6];
?>


Example 3: Output
Array
(
[0] => http://me:you@sub.site.org:29000/pear/validate.html?happy=me&sad=you#url
[1] => http
[2] => me
[3] => you
[4] => sub.site.org
[5] => 29000
[6] => /pear/validate.html
[7] => happy=me&sad=you
[8] => url
)
Path: /pear/validate.html

Example 3: Explain output

$output[0] = full url
$output[1] = scheme or '' if no scheme was found
$output[2] = username or '' if no auth username was found
$output[3] = password or '' if no auth password was found
$output[4] = domain name or '' if no domain name was found
$output[5] = port number or '' if no port number was found
$output[6] = path or '' if no path was found
$output[7] = query or '' if no query was found
$output[8] = fragment or '' if no fragment was found


Example 4: Code

<?php
$url = 'http://me:you@sub.site.org:29000/pear/validate.html?happy=me&sad=you#url';

echo 'SERVER_PROTOCOL: '.$_SERVER['SERVER_PROTOCOL'];
echo 'SERVER_NAME: '.$_SERVER['SERVER_NAME'];
echo 'SERVER_PORT: '.$_SERVER['SERVER_PORT'];
echo 'PHP_SELF: '.$_SERVER['PHP_SELF'];
echo 'REQUEST_URI: '.$_SERVER['REQUEST_URI'];
?>


Example 4: Output

SERVER_PROTOCOL: HTTP/1.1
SERVER_NAME: sub.site.org
SERVER_PORT: 29000
PHP_SELF: /pear/validate.html
REQUEST_URI: /pear/validate.html?happy=me&sad=you#url


Example 5: Code
function getcurrentpath()
{   $curPageURL = "";
    if ($_SERVER["HTTPS"] != "on")
            $curPageURL .= "http://";
     else
        $curPageURL .= "https://" ;
    if ($_SERVER["SERVER_PORT"] == "80")
        $curPageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     else
        $curPageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        $count = strlen(basename($curPageURL));
        $path = substr($curPageURL,0, -$count);
    return $path ;
}
 
echo getcurrentpath();


Example 5: Output

If current URL is:
http://www.abc.com/file/demo1/contact.html

Output will be:
http://www.abc.com/file/demo1/

Refer: http://blog.vivekv.com/php-get-the-current-url-path.html

Monday, July 22, 2013

CSS: Crop and resize image to certain ratio

Edit margin and move the image around within the <div> container.

<style>
.crop {
    width: 200px;
    height: 150px;
    overflow: hidden;
}

.crop img {
    max-width: 400px;
    height: auto;
    margin: -75px 0 0 -100px;
}
</style>
<div class="crop">
    <img src="http://img1.jurko.net/wall/paper/donald_duck_4.jpg" />
</div>

Demo 

Refer:
http://stackoverflow.com/questions/493296/css-display-an-image-resized-and-cropped
http://dabblet.com/gist/4711695

Monday, January 7, 2013

PHP: Remove intersect element(s) in array

$array1 = array('abc', 'efg', 'hij', 'klm', 'nop', 'qrs');
$array2 = array('tuv', 'abc', 'wxyz', 'qrs', 'hij');


// Find intersection
$intersection = array_intersect($array1, $array2); 

echo '<pre>'.print_r($intersection, true).'</pre>';
/* output: 
Array
(
    [0] => abc
    [2] => hij
    [5] => qrs
)
*/

// Extract
if(!empty($intersection)){

   foreach ($intersection as $key => $value) {
      unset($$array1[$key]);
   }

}

echo '<pre>'.print_r($array1, true).'</pre>';
/* output: 
Array
(
    [1] => efg
    [3] => klm
    [4] => nop
)
*/

Refer site:
Unset - http://sg2.php.net/manual/en/function.unset.php
Array intersect - http://php.net/manual/en/function.array-intersect.php

Thursday, November 1, 2012

Tuesday, October 9, 2012

CSS: hasLayout hack

Clear float using "clear:both;"

<style>
ul {
 list-style: none;
}

ul li {
 float:left; 
 width:100px; 
 border:1px solid #ccc; 
 margin-right:5px; 
 text-align:center;
}

.clear {
 clear:both;
}

.flower {
 color:red;
 font-weight:bold;
}
</style>

<ul>
<li>coffee</li>
<li>tea</li>
<li>water</li>
</ul>

<div class="clear"></div>
<div class="flower">rose</div>

Add either width or height with a overflow hidden, it should cleared the float, without adding "clear:both;"

<style>
ul {
 list-style: none; 
 width:100%; 
 overflow: hidden;
}

ul li {
 float:left; 
 width:100px; 
 border:1px solid #ccc; 
 margin-right:5px; 
 text-align:center;
}

.clear {
 clear:both;
}

.flower {
 color:red; 
 font-weight:bold;
}
</style>

<ul>
<li>coffee</li>
<li>tea</li>
<li>water</li>
</ul>

<div class="clear"></div>
<div class="flower">rose</div>




Refer site: http://chatter.customdesigns.com.au/?p=123

Friday, September 14, 2012

JavaScript: Array vs. Objects

Regular Array Object/Associate Array
// regular array (add an optional integer argument to control array's size)
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
//Create a direct instance of an object
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
// create literal array
var myCars=["Saab","Volvo","BMW"];
//create alternative syntax (using object literals): 
personObj = {firstname:"John", lastname:"Doe", age:50, eyecolor:"blue"};
// find total length of array
document.write(myCars.length);
// output: 3
Object.size = function(obj) {
   var size = 0, key;
   for (key in obj) {
     if (obj.hasOwnProperty(key)) size++;
   } 
   return size;
};
document.write(Object.size(personObj));
// output: 4
// print individual element of array
document.write(myCars[0]);
// output: Saab
document.write(personObj['firstname']);
// output: John
document.write(personObj.firstname);
// output: John
// print all elements of array
for(var x = 0; x < myCars.length; x++){
     document.write(myCars[x] + " ");
}
// output: Saab Volvo BMW
var x;
for (x in personObj) {
     document.write(personObj[x] + " ");
}
// output: John Doe 50 blue

Refer site:
http://www.w3schools.com/js/js_obj_array.asp
http://www.w3schools.com/js/js_objects.asp

Wednesday, May 2, 2012

JavaScript: Split a string and store into array

Example 1:
<script type="text/javascript">
var myString = "123456789";
var mySplitResult = myString.split("5");
document.write("The first element is " + mySplitResult[0]); 
document.write("
 The second element is  " + mySplitResult[1]); 
</script>
Output 1:
The first element is 1234
The second element is 6789
Example 2:
<script type="text/javascript">
 var cars = 'bmw,audi,honda,chrysler';
 var split_cars = cars.split(',');
 for (var i = 0; i < split_cars.length; i++) {
  document.write(split_cars[i] + '
'); // print all words
 }
</script>
Output 2:
bmw
audi
honda
chrysler

Refer site:
http://www.w3schools.com/jsref/jsref_split.asp
http://www.alexxoid.com/blog/dev/javascript-dev/how-to-explode-the-string-in-javascript.html

Monday, March 26, 2012

PHP: Split string using array

Example 1:
<?php
 $str = "How are you doing today?";
 $split_str = explode(" ", $str);
 echo '<pre>'.print_r($split_str, true).'</pre>'; // Output 1
 echo $split_str[1]; // Output 2
?>
Output 1
Array
(
    [0] => How
    [1] => are
    [2] => you
    [3] => doing
    [4] => today?
)
Output 2
are

Example 2:
<?php
$string = '<span style="font-weight: bold;">Lorem ipsum dolor sit amet:-</span><br>(1) consectetur adipisicing elit <br>(2) sed do eiusmod tempor <br>(3) incididunt ut labore et <br>(4) dolore magna aliqua';
echo '<p>'.$string.'</p>'; // Output 3

$chars = preg_split('/<br>/', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
$third_br_position = $chars[3][1];  
$description = substr($string, 0, $third_br_position);

echo '<p>'.$description.'</p>'; // Output 4
?>
Output 3
Lorem ipsum dolor sit amet:-
(1) consectetur adipisicing elit 
(2) sed do eiusmod tempor 
(3) incididunt ut labore et 
(4) dolore magna aliqua
Output 4
Lorem ipsum dolor sit amet:-
(1) consectetur adipisicing elit 
(2) sed do eiusmod tempor 

Refer site:
explode() - http://php.net/manual/en/function.explode.php
preg_split() - http://php.net/manual/en/function.preg-split.php
http://www.java-samples.com/showtutorial.php?tutorialid=938

Monday, March 19, 2012

HTML: Automatically Fill in Email Subject (mailto)

Example 1: <a> tag
<a href="mailto:emailname@yourdomain.com?subject=Subject You Selected&body=Body content">The text of your link</a>

Example 2: open new window in JavaScript
window.open('mailto:emailname@yourdomain.com?subject=Subject You Selected&body=Body content');

Example 3: <form> tag | (Demo)
<form action="mailto:you@yourdmainhere.com" method="post" enctype="text/plain">
FirstName:<input type="text" name="FirstName">
Email:<input type="text" name="Email">
<input type="submit" name="submit" value="Submit">
</form>

Refer site:
http://www.htmlbasictutor.ca/email-subject.htm
http://www.javascript-coder.com/javascript-form/javascript-email-form.phtml

Sunday, January 8, 2012

CSS: Image always stick to left/right

File: styles.css
<style>
.btn_right {
 width: 50px; 
 height: 112px; 
 position: fixed; 
 right: 0pt; 
 top: 62px; 
 margin: 0px; 
 display: block;
}

.btn_left {
 width: 50px; 
 height: 112px; 
 position: fixed; 
 left: 0px; 
 top: 50%; 
 margin: -45px 0px 0px; 
 cursor: pointer; 
 display: block;
}

.btn_close_right {
 display: inline-block; 
 margin-left:30px; 
 width: 20px; 
 height: 18px; 
 background: url('close_icon.png') 0px 0px no-repeat; 
 cursor:pointer;
}
</style>

File: buttons.html
<link rel="stylesheet" type="text/css" href="styles.css" />
<!-- button always stick right -->
<div class="btn_right">
 <img style="cursor:pointer;" src="btn_right.png">
 <br>
 <div class="btn_close_right"></div>
</div>

<!-- button always stick left -->
<div class="btn_left">
 <img src="btn_left.png">
 <br>
 <img src="close_icon.png">
</div>

Positioning Tutorial: http://www.barelyfitz.com/screencast/html-training/css/positioning/

Monday, January 2, 2012

Monday, December 19, 2011

PHP: Simple Pagination in MySQL I

File: booklist.php
<?php
// booklist.php?page=10
$start_page = (empty($_GET['page'])) ? '0' : $_GET['page'];

function pagination(){
 $sql = mysql_query("SELECT * FROM books ORDER BY id"); 
 $result = mysql_num_rows($sql);
 $counter = $result / 10;
 $paginate = substr($counter, 0, strpos($counter, '.'));

 for($i = 0; $i <= $paginate; $i++){
  $pages = $i * 10;
  $pg_num = $i + 1;
  echo '<a href="booklist.php?page='.$pages.'">'.$pg_num.'</a> ';
 }

 return '<br />Total: '.$result;
}

$sql = mysql_query("SELECT * FROM books ORDER BY id LIMIT $start_page, 10");

// database fields
$fields = "id,title,description,created";
$fields_array = explode(',',$fields);
 
// display
echo '<table border="1">';

echo '<tr>';
foreach($fields_array as $key=>$field){   
 echo '<th>'.$field.'</th>';  
}
echo '</tr>';
 
while($row = mysql_fetch_assoc($sql)){ 
 foreach($fields_array as $key=>$field){
  $field_name = (empty($row[$field])) ? '0' : $row[$field];
  echo '<td align="center">'.$field_name.'</td>'; 
 }
}

// pagination 
echo '<tr><td colspan="4">'.pagination().'</td></tr>';
echo '</table>';
?>