Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Randomly select an entry in a multidimensional array

Status
Not open for further replies.

spelltwister

Programmer
May 12, 2005
36
US
Hello,

Here's the problem. I have a multidimensional array that has typical data of:

{"infantry","infantry","knight"
7 , 4 , 2
"poland" ,"german" ,"russian" }

I need to be able to randomly select a unit by the first field, "type". Is there a way to do this? Thanks so much for help on the problem.
 
Can you give me another description of your data structure? Your current description looks like you have a flat array that you are interpreting as a multidimensional array.

Were I trying to store that type of data, I might do something like:

$a = array
(
array ('type' => 'infantry', 'other' => 7, 'country' => 'poland),
array ('type'=> 'infantry', 'other' => 4, 'country' => 'germany'),
array ('type'=> 'knight', 'other' => 2, 'country' => 'russia')
);


I would then think of this as an array of records. Each record would be stored in numerical elements of the array, and each record would itself be an associative array with all the values in it.

Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Yes, that is what I have, it works like this:

$offense = array( "type" => array(), "number" => array(), "nation" => array() );
$defense = array( "type" => array(), "number" => array(), "nation" => array() );
if($ally == 2 && $ally2 == 2){
$defense["type"][] = $type;
$defense["number"][] = $number;
$defense["nation"][] = $nation;
}else{
$offense["type"][] = $type;
$offense["number"][] = $number;
$offense["nation"][] = $nation;
}
, but I posted it like that for an example of what the data might look like. I need help gathering data randomly by the type.

Example. If an infantry unit is killed, i need to select randomly from the array, an infantry unit and reduce the number by one, and if it drops to zero, delete that entry.

Thanks so much for any help!!

Mike
 
I don't know if my datastructure is necessarily any more efficient than yours, but I could readily change mine to add greater complexity to the structure which would likely make the structure-manipulating code simpler:

Code:
$defense = array 
(
	'infantry' => array
	(
		array ('strength' => 7, 'country' => 'poland),
		array ('strength' => 4, 'country' => 'germany')
	),
	'knight' => array
	(
		array ('strength' => 2, 'country' => 'russia')
	)
);

With this structure, it would be easier to randomly find one example of a particular unit-type and "downgrade" its strength.

Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top