dourang20110122 2011-01-16 19:50
浏览 175
已采纳

从foreach()循环和print_r()返回数组

I am doing some study on arrays, and I am trying to resolve how to store the values of a foreach loop into an array which I can then print_r().

My script works fine with the exception of the $array = foreach()... And as you can see I called return; to return the results to the $array variable, but I am getting a parse error.

Here is my code so far:

<?php

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <input type="radio" name="DataNameOne" value="Value 1">
  <input type="radio" name="DataNameTwo" value="Value 2">
  <input type="radio" name="DataNameThree" value="Value 3">
  <input type="submit" />
</form>
<?php

$array = foreach ($_POST as $key=>$value) {
    if (stristr($key, "section")) {
        $section = $value;
        $section_name = $key;
        return;
    }
    echo "Key is: $key and Valus is: $value";
}

echo "<pre>";
print_r($array);
echo "</pre>";

?>
  • 写回答

3条回答 默认 最新

  • dtnd30892 2011-01-16 19:53
    关注

    You could just do

    $array = $_POST;
    

    since $_POST is already an array. However if you want to use the foreach loop to iterate a source array and copy only certain parts of it, you'd do something like:

    $new_array = array()
    foreach($original_array as $key => $value) {
        if (...filter condition(s)...) {
            $new_array[$key] = $value;
        }
    }
    

    There's also array_map(), preg_grep(), etc... which you mangle/filter array as you please.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题