2010-08-20 16 views
0

Comment faire du code ci-dessous une fonction?PHP: Faire de la boucle et des variables variables une fonction

# split the string by string on boundaries formed by the string delimiter will split the value into an array like the example below, 
# Array 
# (
#  [0] => pg_cat_id=1 
#  [1] => tmp_id=4 
#  [2] => parent_id=2 
#) 
$array_parent = explode("&", $string); 
//print_r($array_parent); 

# now loop the array. 
for($i = 0; $i < count($array_parent); $i++) 
{ 
    # split the array into smaller arrays with the string delimiter, like the example below, 
    # Array 
    # (
    #  [0] => pg_cat_id 
    #  [1] => 1 
    # ) 
    # Array 
    # (
    #  [0] => tmp_id 
    #  [1] => 4 
    # ) 
    # Array 
    # (
    #  [0] => parent_id 
    #  [1] => 2 
    # ) 
    $array_child = explode("=", $array_parent[$i]); 
    //print_r($array_child); 

    # loop each of the array. 
    for($a = 0; $a < count($array_child); $a++) 
    { 
     # get the first value in each array and store it in a variable. 
     $v = $array_child[0]; 

     # make the variable variable (sometimes it is convenient to be able to have variable variable names. 
     # that is, a variable name which can be set and used dynamically. a variable variable takes the value 
     # of a variable and treats that as the name of a variable). 
     ${$v} = $array_child[1]; 
    } 
} 

afin que je puisse appeler la fonction chaque fois que je besoin, comme ci-dessous,

$string = 'pg_cat_id=1&tmp_id=4&parent_id=2'; 

echo stringToVarVars($string); 

echo $tmp_id; // I will get 4 as the restult. 

Un grand merci, Lau

+3

Ne faites pas cela. N'essayez pas de ré-implémenter ['register_globals'] (http://php.net/manual/en/security.globals.php) ... – ircmaxell

Répondre

2

Code de travail complet ici. Pas besoin de créer une fonction. Juste deux lignes de codes suffisent.

<?php 
$string = 'pg_cat_id=1&tmp_id=4&parent_id=2'; 

parse_str($string, $result); 
extract($result); 

echo $tmp_id; // output: 4 
?> 
+0

oh merci beaucoup. Cela économise beaucoup de mon code fastidieux! merci :) – laukok

+0

De rien. – shamittomar

1

Utilisez le de mot-clé global pour définir des variables en dehors de la fonction.

function stringToVarVars($string) 
{ 
    ... 
    global ${$v}; 
    ${$v} = ...; 
} 
3

Etes-vous en train d'analyser une chaîne de requête? Vous pouvez utiliser parse_str().

0

Utilisez un tableau au lieu de variables variables:

function stringToVarVars($string) 
{ 
    ... 
    $result[$v] = ...; 
    return $result; 
} 

$variables = stringToVarVars($string); 
echo $variables['tmp_id']; 
+0

Je ne sais pas pourquoi vous n'avez pas combiné vos deux réponses similaires en une seule. Espérant doubler dip sur upvotes? Peut-être juste supprimer celui-ci et fusionner les réponses dans le upvoted. – mickmackusa