воскресенье, 25 марта 2012 г.

array_rand function alternative


Strange thing happened with array_rand function after PHP 5.2.10 Release... I should paste it from official site:

"The resulting array of keys is no longer shuffled." 
C'mon i dont even understand now how it works. Anyway some good man make good and also elegant alternative, when you need to shuffle an array and take some entries from it.

 <?php  
 function array_random($arr, $num = 1) {  
   shuffle($arr);  
     
   $r = array();  
   for ($i = 0; $i < $num; $i++) {  
     $r[] = $arr[$i];  
   }  
   return $num == 1 ? $r[0] : $r;  
 }  
   
 $a = array("apple", "banana", "cherry");  
 print_r(array_random($a));  
 print_r(array_random($a, 2));  
 ?>  

среда, 7 марта 2012 г.

taxonomy name save programmatically

Drupal 7 In this tick we will save taxonomy name into node taxonomy field programmaticaly.
Basic data:

  • taxonomy name (ex. 'John Doe')
  • taxonomy field (ex. field_term)
Conditions:
  • we dont have this taxonomy name in our vocabulary
  • we have this taxonomy name in our vocabulary
Problem:
  • Drupal taxonomy field saves only 'tid' not title
Soliution is simple. We must save not existing taxonomy name before programmaticall node save.
Here is some (maybe not perfect) code:

 $term_name = 'John Doe';  
 $term_array = taxonomy_get_term_by_name($term_name);  
 if($term_array == array()) { # empty term .. we can save new taxonomy  
      $term->name = $term_name;   
      $term->vid = 1;   
      taxonomy_term_save($term); # here  
      $term_array = taxonomy_get_term_by_name($term_name); # call agaim, we need a 'tid' for save  
      foreach ($term_array as $tid => $term_object)  
      break;   
      $node->field_term[$node->language][0]['tid'] = $term_object->tid;  
       } else {  
       $term_array = taxonomy_get_term_by_name($term_name);  
      foreach ($term_array as $tid => $term_object)  
      break;   
           $node->field_term[$node->language][0]['tid'] = $term_object->tid;  
      }  

вторник, 6 марта 2012 г.

php string function


Elegant way to extract certain words or letters from a string. Found at php.net.
 <?php  
 /* subtok(string,chr,pos,len)  
  *  
  * chr = chr used to seperate tokens  
  * pos = starting postion  
  * len = length, if negative count back from right  
  *   
  * subtok('a.b.c.d.e','.',0)   = 'a.b.c.d.e'  
  * subtok('a.b.c.d.e','.',0,2)  = 'a.b'  
  * subtok('a.b.c.d.e','.',2,1)  = 'c'  
  * subtok('a.b.c.d.e','.',2,-1) = 'c.d'  
  * subtok('a.b.c.d.e','.',-4)  = 'b.c.d.e'  
  * subtok('a.b.c.d.e','.',-4,2) = 'b.c'  
  * subtok('a.b.c.d.e','.',-4,-1) = 'b.c.d'  
  */  
 function subtok($string,$chr,$pos,$len = NULL) {  
  return implode($chr,array_slice(explode($chr,$string),$pos,$len));  
 }  
 ?>