I have a multidimensional array that works if I manually set the values, but does not work if I try to dynamically set the values.
Here is the code that works when I manually set the array values:
<?php
//testing creation and output of a multidimensional array
$evt = array("BATT","MGAP","BSTR");
$st = array("Document","Enrollee","Agent","Other");
$ord = array(1,3,2,4);
$prt = array(
array('evt'=>"BATT",'st'=>"Document",'ord'=>1),
array('evt'=>"BATT",'st'=>"Enrollee",'ord'=>3),
array('evt'=>"BATT",'st'=>"Agent",'ord'=>2),
array('evt'=>"BATT",'st'=>"Other",'ord'=>4),
array('evt'=>"MGAP",'st'=>"Document",'ord'=>1),
array('evt'=>"MGAP",'st'=>"Enrollee",'ord'=>3),
array('evt'=>"MGAP",'st'=>"Agent",'ord'=>2),
array('evt'=>"MGAP",'st'=>"Other",'ord'=>4),
);
$keys = array_keys($prt);
for ($x=0;$x<count($keys);$x++) {
echo "UNSORTED: prt key is " . $keys[$x] . "{<br>";
foreach ($prt[$keys[$x]] as $key=> $value) {
echo $key . " : " . $value . "<br>";
}
echo "}<br>";
}
?>
Here is the code that does not work when trying to dynamically set the values:
<?php
//testing creation and output of a multidimensional array
$evt = array("BATT","MGAP","BSTR");
$st = array("Document","Enrollee","Agent","Other");
$ord = array(1,3,2,4);
$prt = array();
for ($x=0;$x<count($evt);$x++) {
for ($y=0;$y<count($st);$y++) {
$prt[$x][$y] = array('evt'=>$evt[$x],'st'=>$st[$y],'ord'=>$ord[$y]);
echo "evt[".$x."] is set to " . $evt[$x] . " and st[".$y."] is set to " . $st[$y] . " and ord[".$y."] is set to " . $ord[$y] . "<br>";
}
}
$keys = array_keys($prt);
for ($x=0;$x<count($keys);$x++) {
echo "UNSORTED: prt key is " . $keys[$x] . "{<br>";
foreach ($prt[$keys[$x]] as $key=> $value) {
echo $key . " : " . $value . "<br>";
}
echo "}<br>";
}
?>
Based on the echo statement within the for $y loop, I am getting the right values, but for some reason I am either not storing it correctly, or the foreach loop using $key=>$value isn't working, and I can't figure out which. I have looked for various solutions to try to set the array dynamically and then access it again dynamically and can't seem to get it to work as expected. I hope you all can help, thanks!
Change this line
$prt[$x][$y] = array('evt'=>$evt[$x],'st'=>$st[$y],'ord'=>$ord[$y]);
to this:
$prt[] = array('evt'=>$evt[$x],'st'=>$st[$y],'ord'=>$ord[$y]);
$ptr
should be a "flat" array of arrays. In the original code line, what you're actually creating is a multidimensional array, which doesn't work as expected.