3

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:

  1. populate it with data from MySQL database
  2. display it/reffer to it like: 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];
}
}
}
3
  • Why do you need a multidimensional array? Commented Sep 13, 2012 at 11:35
  • Thats not related with nature of my question Commented Sep 13, 2012 at 11:53
  • 2
    It's often more convenient to have a clear view of the context of a question, and sometimes it allows us to give a better answer with an alternative approach to the problem. In that case I could have suggested a OOP alternative with a 3dPoint class and mysql_fetch_object for example. It is also considered nice to answer people willing to help you when they request clarification. Commented Sep 13, 2012 at 12:02

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

8 Comments

How to test your code with $db = mysql_connect($db_host,$db_user,$db_password) or die($error[0]);? Also I get Undefined function SQLFetchRow
I have updated my answer; you'll need to supply DB connection parameters and exact query syntax for it to be acceptable.
Fatal error: Call to undefined function mysql_free() in pastebin.com/s9dPiJRX on line 44
Ah, sorry. it was mysql_free_result().
How to alter it to echo values (inside while-loop) only if they are actually in DB?
|
0

mysql_fetch_assoc($pullMapInfo2) will return an array that you can use to get the X,Y, and Z values of your player like so:

$x = $pullMapInfo3["x"]
$y = $pullMapInfo3["y"]
$z = $pullMapInfo3["z"]

If you want to put that in your result_value array you can the simply $result_value[$x][$y][$z] = $pullMapInfo3["value"].

Also, move the initialization of $result_value out of the loop to where you wrote $result_value = array();:

for ($ix = 1; $ix <= 16; $ix++) {
    $result_value[$ix] = array();
    for ($iy = 1; $iy <= 16; $iy++) {
        $result_value[$ix][$iy] = array();
    }
}

Then you can use the loop from the pastebin. Also note that you're just going to get Layer 1, Layer 2, Layer 3 at the output + 768 <br> tags, so I'm not sure if that's what you meant to do.

4 Comments

This lags a little and outputs Layer 1: pastebin.com/sJJsJrfF
It did that because you don't instantiate the subarrays. You just set $result_value to array(), which means it's 1 dimensional. First thing in the iz loop: $result_value[$iz]=array(), then in the ix loop: $result_value[$iz][$ix] = array(). Note that this will mean its addressing will be ...[z][x][y]. If you want it to be [x][y][z], you'll have to write a separate loop to build up the arrays before using them. It's only outputting layer 1 because it fails to do the first $result_value[$x][$y][$z] lookup after entering the loop.
New code in the edit shows how to set up $result_value. Put that right after $result_value = array()
This (pastebin) displays Layer 1, Layer 2, and Layer 3. I've used dummy values. Check to see that the x,y, and z you're getting from the database are in the proper ranges.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.