<?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.
}
}
?>

如何在php中将值推送到数组中
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
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; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报