I currently have 2 separate arrays that are related to each other. Both are populated dynamically during a series of loops.

The first is a 2 dimensional array that contains lists of properties. Each list of properties is used to define who goes into the same index in the second array. Conversely, the 2nd array, also a 2-dimensionsal array, contains lists of student objects meeting the criteria in the matching index in the first array.

It occurred to me that I could combine these two arrays into a 3-dimensional array

$corral = array();
$corral[$i}['prop1'] = 'a';
$corral[$i]['prop2'] = 'b';
$corral[$i]['prop3'] = 'c';
$corral[$i]['students'] = array();

Before diving in, I researched the net and the archives here. I didn't find a primer that packaged 3-dimensional array info in one place. I have some common questions related to 3-dimensional arrays plus the code it seems would answer it. Would someone check my syntax (and add anything I might have left out)? I'd hated to start implementing and then find out I was looking at the whole thing cockeyed.

	// Add items to $corral[$i]['students']?
	$corral[$i]['students'][] = $studentObject;
	# OR
	$corral[$i]['students'][33] = $studentObject;

// Get a count of $corral[$i]['students']?
$nStudents = count ( $corral[$i]['students'] );


// Get a property of the object INSIDE the array
$lastName = $corral[$i]['students'][12]->get_nameLast();

// Set a property of the object INSIDE the array, in this case
$corral[$i]['students'][12]->set_nameLast( $newName );

    FYI,

    $corral[$i]['students'][33] = $studentObject;

    could also be written like this:

    $corral = array($i => array("students" => array(33 =>$studentObject)));
    

      I do not see anything wrong with your syntax.

      Note that reddrum's suggestion can only be used to initialize the array. To add elements to an existing array you must use the $array[ix1][ix2][ix3] = 'value'; syntax, as the array() syntax will wipe out any pre-existing values within the array. But it can be useful when initially defining an array.

        Write a Reply...