Szymon Toda
Szymon Toda

Reputation: 4516

Why PHP 3D Array has 'z' not be defined?

Pulled data below should return:

But as last line var_dump($result_value); returns with no z:

What am I missing here for having 'z' in $result_value?

    $pullMapInfo = "SELECT x, y, z, value FROM mapinfo WHERE id='{$player_id}'";
    $pullMapInfo2 = mysql_query($pullMapInfo) or die($error[4]);

    //create an array with all x, y, z
    for ($y = 1; $y <= 16; $y++) $array_y[] = $y;
    for ($x = 1; $x <= 16; $x++) $array_x[] = $x;
    for ($z = 1; $z <= 3; $z++) $array_z[] = $z;

    //create an associative array x, y, z => value
    $result_value = array();
    while ( $pullMapInfo3 = mysql_fetch_assoc($pullMapInfo2) ) {
        $result_value[ $pullMapInfo3['x'] ][ $pullMapInfo3['y'] ][ $pullMapInfo3['z'] ] = $pullMapInfo3['value'];
    }

    //loop to display output
    foreach ($array_z as $z) {
        echo '<div class="container">';
    foreach ($array_y as $y) {
    foreach ($array_x as $x) {

        if (array_key_exists($x, $result_value) && array_key_exists($y, $result_value[$x] )) {
            echo '<div class="tileBox pos_',$result_value[$x][$y][$z] ,'" id="'.$x.','.$y.','.$z.'"></div>';
        } else {
            echo '<div class="tileBox pos_0" id="'.$x.','.$y.','.$z.'"></div>
    ';
        }
    }
    }
        echo '</div>';
    }

    var_dump($result_value);
    #outputs: array(1) { [1]=> array(1) { [1]=> array(1) { [1]=> string(1) "3" } } }
    #as it pulled data from database: x, y, value - it misses z!

Table Structure: id INT(11)

x, y, z TINYINT(2)

value VARCHAR(10)

var_dump($pullMapInfo3) for @Fluffeh:

bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) ... x768 (16x16x3)

Upvotes: 1

Views: 101

Answers (2)

Robbie
Robbie

Reputation: 17710

Z is there. If you split your output down then you can see it has three dimensions, the last is Z

array(
    [x=1] => array(
       [y=1] => array(
            [z=1] => "3"
                     )
                   )

So $result_value[$x][$y][$z] = 3

Upvotes: 2

mtk
mtk

Reputation: 13707

For creating mulit-dimensional array's in php use

$newarr[array_pop($arr)] = 0;
foreach (array_reverse($arr) as $i)
    $newarr[$i] = $newarr;

Check this SO post having more explanation about it.

Upvotes: 0

Related Questions