douwan7382
douwan7382
2010-02-23 22:03

数组到命名变量

已采纳

How can I take: $userarray (which is an array and I know holds 3 values) and put them into 3 seperate variables instead of looping through. There seperated by , (commas) so explode will be in there somewhere.

Say $userfield1, $userfield2, $userfield3?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • duannaoben8011 duannaoben8011 11年前

    I think you may be looking for either the list() or extract() functionality:

    list()

    list($userfield1, $userfield2, $userfield3) = $userarray;
    

    http://php.net/list

    extract()

    extract($userarray); // uses the array keys for variable names
    

    http://php.net/extract

    点赞 评论 复制链接分享
  • douyanqu9722 douyanqu9722 11年前
    extract($userarray, EXTR_PREFIX_ALL, 'userfield');
    

    This will create $userfield_1, $userfield_2, $userfield_3 variables (note the underscores).

    点赞 评论 复制链接分享
  • dpjuppr1361 dpjuppr1361 11年前

    Yes, use the extract method.

    From the docs:

    <?php
    
    $size = "large";
    $var_array = array("color" => "blue",
                       "size"  => "medium",
                       "shape" => "sphere");
    extract($var_array);
    
    echo "$color, $size, $shape";
    
    ?>
    

    The above example will output:

    blue, large, sphere

    Or do you want to glue your elements together? Then try implode:

    $array = array('lastname', 'email', 'phone');
    $comma_separated = implode(",", $array);
    

    Will print:

    "lastname, email, phone"

    点赞 评论 复制链接分享

相关推荐