2009/08/28

sort string field in mysql

A clever way to sort a string field.

Q:
It needs to be ORDER BY attribute. So then we get alphabetical order of non-numerical string (column named attribute) and numerical order for 'attribute' combined with numerical and non-numerical characters. For example,

apple
blueberry
orange

AND

1 foot
2 feet
3 feet

A:
ORDER BY CAST(attribute AS UNSIGNED)

2009/08/27

Remove a member from array and ArrayObject

For arrayobject, you can do
foreach ($arrobj as $obj){
do something ...
}
Like array does.

However you cannot use unset to remove a ArrayObject member, for example,
$hits is ArrayObject,

You could not do something like,
foreach ($hits as $hit) {
if(!preg_match("/.*abc$/", $hit->sku)){
unset($hits[$hit]);
}
}

You have to use ArrayObject's method called append to do it, like,

$new_hits = new ArrayObject();
foreach ($hits as $hit) {
if(!preg_match("/.*CR$/", $hit->sku)){
$new_hits->append($hit);
}
}
$hits = $new_hits;

Object to Array in PHP

If less than PHP5, then use this function,

function objectToArray($object)
{
$array=array();
foreach($object as $member=>$data)
{
$array[$member]=$data;
}
return $array;


If PHP5, then You can cast your object to an array by,

$array = (array) $this;

call native php function in smarty

I bet you know we can use php function in the smarty condition clause, like,
{if count($arr)} do something ... {/if}

But if we want to display array size, we cannot use {count($arr)}, but we can use,
{$arr|@count}

So to call native php function, we can use below format:
{$input_parameter|@native_phpfunction}
Note:
  1. $input_parameter is smarty variable
  2. native_php_function, like sizeof, count, round, etc..

2009/08/25

Trim in perl

Perl does not come with trim function, but you can crate one easily:

# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($)
{
    my $string = shift;
    $string =~ s/\s+$//;
    return $string;
}

PHP4 CLASS VS PHP5

  1. PHP4 classes don't have scope operators such as private, public or
    protected.
  2. PHP4 constructional function should be the same name with that of the class. __construction won't work.
  3. Class variables in PHP4 classes are declared with the keyword 'var' rather
    than private or public.

REF: kavoir.com