parse_str数组仅返回最后一个值

时间:2018-01-31 06:38:08

标签: php ajax

我使用ajax将表单和ajax值提交为:

newcoach=6&newcoach=11&newcoach=12&newcoach=13&newcoach=14

在PHP中我使用 parse_str 将字符串转换为数组,但它只返回最后一个值:

$newcoach = "newcoach=6&newcoach=11&newcoach=12&newcoach=13&newcoach=14";
$searcharray  = array();
parse_str($newcoach, $searcharray);
print_r($searcharray);

结果数组只有最后一个值:

Array
(
    [newcoach] => 14
)

任何帮助将不胜感激......

3 个答案:

答案 0 :(得分:4)

由于您多次设置参数 newcoach ,因此parse_str将仅返回最后一个参数。如果您希望parse_str将变量解析为数组,则需要以这种格式提供' [] '后缀:

select trunc(timestamp_1), count(*)
from table
group by trunc(timestamp_1)
order by 1;

示例:

$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";

<强>输出:

<?php
  $newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]h=12&newcoach[]=13&newcoach[]=14";
  $searcharray  = array();
  parse_str($newcoach, $searcharray);
  print_r($searcharray);
?>

答案 1 :(得分:0)

目前它正在分配最后一个值,因为所有参数都具有相同的名称。

您可以在变量名后使用[],它将创建包含其中所有值的newcoach数组。

$test = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";

echo '<pre>';
parse_str($test,$result);
print_r($result);

O / P:

Array
(
    [newcoach] => Array
        (
            [0] => 6
            [1] => 11
            [2] => 12
            [3] => 13
            [4] => 14
        )

)

答案 2 :(得分:-1)

使用此功能

function proper_parse_str($str) {
  # result array
  $arr = array();

  # split on outer delimiter
  $pairs = explode('&', $str);

  # loop through each pair
  foreach ($pairs as $i) {
    # split into name and value
    list($name,$value) = explode('=', $i, 2);

    # if name already exists
    if( isset($arr[$name]) ) {
      # stick multiple values into an array
      if( is_array($arr[$name]) ) {
        $arr[$name][] = $value;
     }
  else {
    $arr[$name] = array($arr[$name], $value);
  }
}
# otherwise, simply stick it in a scalar
else {
  $arr[$name] = $value;
    }
  }

  # return result array
  return $arr;
}


$parsed_array = proper_parse_str($newcoach);