dtebrq0245 2012-07-02 19:13
浏览 67
已采纳

PHP foreach循环中的数组范围

I am learning PHP and have been agonizing over how to write my code properly. I have a textarea that accepts user input which is several lines of coordinates (PT# Northing Easting) separated by spaces.

I have the form pass the textarea input to a php script to handle it.

I can get a foreach loop to do exactly what I want but only local to the foreach loop, the variables do not get passed to the outside of the loop.

I know this is a global variable scope issue, for the life of me I can't resolve this...

Below is my PHP code, I left out the HTML form I have no issues with it and know the textarea is being passed properly.

**Sample data that I am inputing:
1 728258.24000 774337.29700
2 728232.15735 774277.54650
3 728326.39614 774216.82428**

<?php

$i = 0;
$j = 0;

//The code below explodes my textarea into a string array
//of separated lines.
$textArea = explode("", $_POST['textArea']);
$textNum = array();

//The code below works internally, but the values remain here
//I wanted to get them to the variables below so I can do work
//to them.
foreach ($textArea as $textRows) {

    //The code below explode the lines into elements separated by a space
    $textRow = explode(" ", $textRows);
    foreach ($textRow as $textItem) {
    $textNum[i][j] = $textItem;

    //The code below works within a local context
    echo "(" . $i . " " . $j . ")" . $textNum[i][j] . "</br>";
    $j++;
    }
    $i++;
    $j = 0;
}

//The code below is not receiving values from the foreach loop
//I know this has something to do with the variable scope
//I must be way off in my approach any help would be appreciated!
echo "</br>";
echo "</br> 0 0 " . $textNum[0][0];
echo "</br> 0 1 " . $textNum[0][1];
echo "</br> 0 2 " . $textNum[0][2];
echo "</br> 1 0 " . $textNum[1][0];
echo "</br> 1 1 " . $textNum[1][1];
echo "</br> 1 2 " . $textNum[1][2];
echo "</br> 2 0 " . $textNum[2][0];
echo "</br> 2 1 " . $textNum[2][1];
echo "</br> 2 2 " . $textNum[2][2];
echo "</br> 3 0 " . $textNum[3][0];
echo "</br> 3 1 " . $textNum[3][1];
echo "</br> 3 2 " . $textNum[3][2];
?>

I hope I have explained this well enough, and appreciate any help I can get! Thanks!

  • 写回答

2条回答 默认 最新

  • douzong2206 2012-07-02 19:18
    关注

    You, need to prepend $ before your variables, i.e $textNum[$i][$j] instead of $textNum[i][j], also, it's best to initialize $i and $j and set them to 0 before the foreach loop.

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

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教