【问题标题】:PHP: Make the loop and variable variables into a functionPHP:将循环和变量变量变成一个函数
【发布时间】:2011-04-01 15:53:32
【问题描述】:

我怎样才能把下面的代码变成一个函数?

# 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];
    }
}

这样我就可以在需要时调用该函数,如下所示,

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

echo stringToVarVars($string);

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

非常感谢, 刘

【问题讨论】:

标签: php variables function for-loop


【解决方案1】:

您是否在解析查询字符串?你可以使用parse_str()

【讨论】:

    【解决方案2】:

    完整的工作代码在这里。无需创建函数。两行代码就够了。

    <?php
    $string = 'pg_cat_id=1&tmp_id=4&parent_id=2';
    
    parse_str($string, $result);
    extract($result);
    
    echo $tmp_id;  // output: 4
    ?>
    

    【讨论】:

    • 哦,非常感谢。这节省了我很多乏味的代码!谢谢:)
    【解决方案3】:

    使用 global 关键字在函数之外设置变量。

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

    【讨论】:

      【解决方案4】:

      使用数组代替可变变量:

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

      【讨论】:

      • 我不确定您为什么不将两个非常相似的答案合二为一。希望在赞成票上翻倍?也许只是删除这个并将答案合并到赞成的答案中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多