Jump to content

need an example using php_rand on a multidimensional array please


silverglade

Recommended Posts

Hi, I am trying to get a random monster from my multidimensional "monsters" array. I have array monsters, and inside that I have array "ocean" and inside that are "fish", "shark" etc.

like the below, and I am trying to pick out a random monster from the Ocean array. Any help greatly appreciated. thank you. Derek

 

here is the array

 

$monsters = array
(
'Ocean'=>array
(
	'octalisk'=>array
	(
		'name'=>'octalisk',
		'hp'=>100,
		'damageLow'=>1,
		'damageHigh'=>15,
		'exp'=>10,
		'ac'=>'HAVE TO LOOK THIS UP',
		'monsterInitiativeModifier'=>'HAVE TO LOOK THIS UP'),

	'shark',
	'eel'
),
'Desert'=>array
(
	'sand_snake'
),
'Forest'=>array
(
	'frog',
	'lizard',
	'spider'
)
);

Link to comment
Share on other sites

Multi- dimensional arrays are a little more difficult to work with in this way.

 

Try something like this:

<?php
$monsters = array
(
   'Ocean'=>array
   (
      'octalisk'=>array
      (
         'name'=>'octalisk',
         'hp'=>100,
         'damageLow'=>1,
         'damageHigh'=>15,
         'exp'=>10,
         'ac'=>'HAVE TO LOOK THIS UP',
         'monsterInitiativeModifier'=>'HAVE TO LOOK THIS UP'),
   
      'shark',
      'eel'
   ),
   'Desert'=>array
   (
      'sand_snake'
   ),
   'Forest'=>array
   (
      'frog',
      'lizard',
      'spider'
   )
);
$random = array_rand($monsters);
$monster = array_rand($monsters[$random]);

if(is_array($monsters[$random][$monster])) {
$currentMonster = $monsters[$random][$monster]['name'];
}
else {
$currentMonster = $monsters[$random][$monster];
}

echo $currentMonster;

?>

Link to comment
Share on other sites

The code works great, only one problem, it echoes out random monsters from the monsters array, and I wanted it to echo out random monsters from the "Ocean" array that is inside of it, so I can generate random encounters when a person enters a certain habitat. Any more help GREATLY appreciated. Thanks for the code. Derek

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.