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条)

报告相同问题?

悬赏问题

  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面