I have a form, where a user inputs alot of different data, among other amount of iterations and amount of asked people. This that my function has to do a multidimensional array with a undefined number of "subarrays".
Basicly, what I want is to make a large array, that has $amount_of_iterations subarrays, which each has $amount_of_asked_people values.
However, I've tried to make this code, which doesnt work:
$my_multidimensional_array = array();
$x = "";
for ($i = 0; $i < $amount_of_iterations; $i++)
{
for ($p = 0; $p < $amount_of_asked_people; $p++)
{
$x = rand();//actually an other function, but this will do for testing
$my_multidimensional_array[$i] = array($p =&开发者_StackOverflow中文版gt; $x);
}
}
//But when i test it i get an error. Here is my testing code:
for ($i = 0; $i < $amount_of_iterations; $i++)
{
echo "<h1>Iteration number $i:</h1>";
for ($p = 0; $p < $amount_of_asked_people; $p++)
{
echo "<br />The Random value is: $my_multidimensional_array[$i][$p]";
}
}
(I've modified the real variable names and function for privacy, but this should work for testing.)
When i echo this, i only get this(where as i should get something like "The Random value: 7771"):
Iteration number 0:
The Random value: Array[0]
The Random value: Array[1]
etc.
Iteration number 1:
The Random value: Array[0]
The Random value: Array[1]
etc.etc.
Two problems:
Every time you iterate over the following line, you're clobbering result of any previous iteration for a given $i
:
$my_multidimensional_array[$i] = array($p => $x);
Rewrite it as:
if(!isset($my_multidimensional_array[$i])) $my_multidimensional_array[$i] = array();
$my_multidimensional_array[$i][$p] = $x;
Additionally, in your test, you're not accessing the array variable correctly in your output string. Use one of the following methods instead:
echo "<br />The Random value is: {$my_multidimensional_array[$i][$p]}";
// or
echo "<br />The Random value is: ".$my_multidimensional_array[$i][$p];
When you use array variable in quotes, you need to surround them with {}
if you want to make sure it's properly parsed.
echo "<br />The Random value is: {$my_multidimensional_array[$i][$p]}";
精彩评论