Friday, 9 January 2015

PHP to limit a text string to a number of words

function limit_words($string, $word_limit)
                     {
                      $words = explode(" ",$string);
                      return implode(" ",array_splice($words,0,$word_limit));
                     }
  echo limit_words($content,20);

Thursday, 8 January 2015

gravity forms related link

The json_decode() PHP function converts JSON data to PHP array data. 

json_decode( data, dataTypeBoolean, depth, options )

Parameters

data
The json data that you want to decode in PHP.
dataTypeBoolean 
Optional boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth
Optional recursion limit. Use an integer as the value for this parameter.
options
Optional JSON_BIGINT_AS_STRING parameter.

<?php
$jsonData = '{ "user":"John", "age":22, "country":"United States" }';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) { 
    echo "<p>$key | $value</p>";
}
?>

<?php
$jsonData = '{ 
"u1":{ "user":"John", "age":22, "country":"United States" },
"u2":{ "user":"Will", "age":27, "country":"United Kingdom" },
"u3":{ "user":"Abiel", "age":19, "country":"Mexico" }
}';
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) { 
    echo "<h2>$key</h2>";
    foreach ($value as $k => $v) { 
        echo "$k | $v <br />"; 
    }
}
?>
An example showing how to call in a .json file and parse it using PHP.
<?php
$jsonData = file_get_contents("mylist.json");
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) { 
    echo "<h2>$key</h2>";
    foreach ($value as $k => $v) { 
        echo "$k | $v <br />"; 
    }
}
?>
The contents of mylist.json are below, create the file and place on your web server before you attempt to run the script above.
{ 
  "u1":{ "user":"John", "age":22, "country":"United States" },
  "u2":{ "user":"Will", "age":27, "country":"United Kingdom" },
  "u3":{ "user":"Abiel", "age":19, "country":"Mexico" }, 
  "u4":{ "user":"Rick", "age":34, "country":"Panama" },
  "u5":{ "user":"Susan", "age":23, "country":"Germany" },
  "u6":{ "user":"Amy", "age":43, "country":"France" }
}

Get the value of serialize data

a:12:{
s:7:"country";
s:2:"CA";
s:4:"city";
s:8:"Brampton";
s:5:"state";
s:7:"Ontario";
s:8:"zip_code";
s:6:"L6T4E7";
s:3:"age";
s:13:"25–34 years";
s:8:"blog_url";
s:22:"http://www.blog.com";
s:16:"blog_description";
s:106:"A blog about blogging";
s:15:"monthly_uniques";
s:4:"1000";
s:13:"facebook_page";
s:55:"http://www.facebook.com/myfacebookpage";
s:14:"facebook_likes";
s:3:"1428";
s:15:"twitter_account";
s:31:"http://twitter.com/mytwitterpage";
s:17:"twitter_followers";
s:3:"5849";}
use php function unserialize()

$data = array( 'apple', 'banana', 'orange' );
echo serialize( $data );
// Result is a string we can unserialize into an array:
// a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}

Retrieving serialize data in a php file called using ajax

Your js should be like this:
var str = $("form").serializeArray();
$.ajax({  
    type: "POST",  
    url: "update.php",  
    data: str,  
    success: function(value) {  
            $("#data").html(value);
    }
});
With php you should loop your result array.
$box = $_POST['box'];
foreach ($box as $x) {
    echo $x;
}
Note  -- You have to use serializeArray function in jQuery. Then it will work with this code.

Wednesday, 7 January 2015

date diff in PHP

/ this function is used to calculate date diff
 // PHP strtotime compatible strings
  function dateDiff($time1, $time2, $precision = 6) {
    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
      $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
      $time2 = strtotime($time2);
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
      $ttime = $time1;
      $time1 = $time2;
      $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array('year','month','day','hour','minute','second');
    $diffs = array();

    // Loop thru all intervals
    foreach ($intervals as $interval) {
      // Create temp time from time1 and interval
      $ttime = strtotime('+1 ' . $interval, $time1);
      // Set initial values
      $add = 1;
      $looped = 0;
      // Loop until temp time is smaller than time2
      while ($time2 >= $ttime) {
        // Create new temp time from time1 and interval
        $add++;
        $ttime = strtotime("+" . $add . " " . $interval, $time1);
        $looped++;
      }
      $time1 = strtotime("+" . $looped . " " . $interval, $time1);
      $diffs[$interval] = $looped;
    }
   
    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
      // Break if we have needed precission
      if ($count >= $precision) {
break;
      }
      // Add value and interval
      // if value is bigger than 0
      if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
  $interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
      }
    }

    // Return string with times
    return implode(", ", $times);
  }
// PHP strtotime compatible strings
$arr_new = explode(",",$date_diff);
//print_r($arr_new);
$str =  $arr_new[0];
$months = substr($str,0,-6);

$str1 =  $arr_new[1];
$days = substr($str1,0,-5);

$str2 =  $arr_new[2];
$hours = substr($str2,0,-6);
$str3 =  $arr_new[3];
$minutes = substr($str3,0,-8);
    $str4 =  $arr_new[4];
$seconds = substr($str4,0,-8);

date time difference in php

function datediff( $date1, $date2 )
{
    $diff = abs( strtotime( $date1 ) - strtotime( $date2 ) );

    return sprintf
    (
        "%d Days, %d Hours, %d Mins, %d Seconds",
        intval( $diff / 86400 ),
        intval( ( $diff % 86400 ) / 3600),
        intval( ( $diff / 60 ) % 60 ),
        intval( $diff % 60 )
    );
}

print datediff( "18th February 2013", "now" ) . "\n";



$start_date = new DateTime("2012-02-10 11:26:00");
    $end_date = new DateTime("2012-04-25 01:50:00");
    $interval = $start_date->diff($end_date);
    echo "Result " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

Tuesday, 6 January 2015

Connect to another database in wordpress using wbdb object


The wpdb object can be used to access any database and query any table. Absolutely no need to be Wordpress related, which is very interesting.
The benefit is the ability to use all the wpdb classes and functions like get_results, etc so that there's no need to re-invent the wheel.
Here's how:

$mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("select Name from my_table");
echo "<ul>";
foreach ($rows as $obj) :
   echo "<li>".$obj->Name."</li>";
endforeach;
echo "</ul>";