doure8758 2014-12-11 07:50
浏览 65
已采纳

如何在php中将值推送到数组中

<?php
    $ore = "piece1 piece2 piece3 piece4 piece5 piece6";
    $user = array();
    $alotted = array();

    //splitting string ore.
    $output = preg_split( "/ ( |
) /", $ore );

    //entering even value of array output to user and odd to alotted. 
    for ($x = 0; $x < sizeof($output); $x++) 
    {
        if ($x % 2 == 0) 
        {
            array_push(user,$output[$x]); //trying to put values in array user. 

        } 
        else 
        {
                array_push(alotted,$output[$x]);//trying to put value in alotted.
        }
    } 

?>
  • 写回答

7条回答 默认 最新

  • douluan5523 2014-12-11 07:56
    关注

    First off, if this is not a typo, you forgot the $ signs on:

    array_push($user,$output[$x]);
            // ^ $ 
    array_push($alotted,$output[$x]);
          //   ^
    

    Then on your regex, remove the leading and trailing space:

    $output = preg_split("/( |
    )/", $ore); // space or newline
                       //  ^     ^ // no spaces
    

    Refactored into this:

    $ore = "piece1 piece2 piece3 piece4 piece5 piece6";
    $output = preg_split("/( |
    )/", $ore );
    // $output = explode(' ', $ore);
    $user = $alotted = array();
    for ($x = 0; $x < sizeof($output); $x++) {
        ($x % 2 == 0) ? array_push($user,$output[$x]) : array_push($alotted,$output[$x]);
    } 
    

    I don't know why you have to use a regular expression on this, explode() should suffice in this particular string example.

    Code:

    $ore = "piece1 piece2 piece3 piece4 piece5 piece6";
    foreach(explode(' ', $ore) as $x => $piece) {
        ($x % 2 == 0) ? $user[] = $piece : $alotted[] = $piece;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗