As my previous questions simplify I am trying to learn 3D arrays in PHP but each lesson is getting difficult to understand by me.
I have prepared code with empty 3D (layered) array but don't know how to:
echo $result_value[x][y][z] gives
value.
include_once 'connect.php';
$player_id = '6';
$result_value = array();
$pullMapInfo = "SELECT x, y, z, value FROM mapinfo WHERE id='{$player_id}'";
$pullMapInfo2 = mysql_query($pullMapInfo) or die(mysql_error());
while ( $pullMapInfo3 = mysql_fetch_assoc($pullMapInfo2) ) {
$result_value = array(
array(
array('', '', ''),
array('', '', ''),
array('', '', ''),
),
array(
array('', '', ''),
array('', '', ''),
array('', '', ''),
),
array(
array('', '', ''),
array('', '', ''),
array('', '', ''),
)
);
}
for($z = 1; $z <= 3; $z++){
for($x = 1; $x <= 16; $x++){
for($y = 1; $y <= 16; $y++){
# echo database row's divided among layers (z parameter) for ex.: 1,1,1 = red (X,Y,Z = color value) - 1 width & 1 height on 1st layer contains red value
# to get access to it like this: $result_value[x][y][z] => [value];
}
}
}
populate it with data from MySQL database display it/reffer to it like: echo $result_value[x][y][z] gives value
The population stage is simply selecting at least x, y, z and value fields.
Then, in a loop, you retrieve all the data. At that point you check whether the array prerequisites are present, if they aren't you set them up, and set the value:
<?php
$db = mysql_connect($db_host,$db_user,$db_password) or die($error[0])
$arr3d = array();
/* Initialization to get a "dense" array
$z_row = array_fill(0, $max_z, '<DEFAULT>');
$y_row = array_fill(0, $max_y, $z_row);
$arr3d = array_fill(0, $max_x, $y_row);
unset($y_row, $z_row); // Do not waste memory
*/
$query = 'SELECT x, y, z, value FROM ...;' ;
$handle = mysql_query($query) or die("$query: error: " . mysql_error());
while($row = mysql_fetch_array($handle))
{
// $row is an array with x, y, z and value keys in this order
list($x, $y, $z, $value) = $row;
/* This if we had used mysql_fetch_assoc instead
$x = $row['x'];
$y = $row['y'];
$z = $row['z'];
$value = $row['value'];
*/
if (!isset($arr3d[$x]))
$arr3d[$x] = array();
if (!isset($arr3d[$x][$y]))
$arr3d[$x][$y] = array();
$arr3d[$x][$y][$z] = $value;
}
mysql_free_result($handle);
?>
In case you want a full ("dense") array, you have to first loop x, y and z through all their values and assign a default value to array cells, to be overwritten by the SQL loop.
In the code above, with dense patch left commented, if there is no row with x=5, y=2 and z=3, $arr3d[5][2][3] will be undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With