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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.