Array Node Wondering
11 Nov
This function will walk through an array structure randomly (thus “wondering”). In some instances you may have an array that is structured like a tree. You may also need to randomly build a path from the trunk to the end leaf while mapping all nodes in between. The following function will walk through the nodes while recording the keys in text format :
function node_wonder($in_array,$load=null) {
$keys = array_keys( $in_array );
shuffle( $keys );
$item = current($keys);
if (is_array($in_array[$item])) {
if ($load) $load .= " ";
return node_wonder($in_array[$item],$load.$item);
} else {
if ($load) $load .= " ";
return $load.$in_array[$item];
}
}
As an example, we will use this array :
$testArray = array(
"The dog" => array(
"barked at"=>array(
"the mail man",
"the moon",
"the passing" => array(
"cars",
"trucks",
"people"
),
),
"chased"=>array(
"its tail",
"another dog",
"after the airplane"
),
"wagged its tail"
),
"The cat" => array(
"slept" => array(
"lazily",
"all afternoon",
"curled in a ball"
),
"played with" => array(
"its mouse toy",
"a ball of yarn",
"another cat"
),
),
"The fish" => array(
"swam",
"ate flakes"
)
);
When we pass the $testArray to the node_wonder() function we will get a new story each time :
The dog barked at the passing people The cat played with another cat The fish ate flakes The dog chased after the airplane The fish swam The dog barked at the mail man The cat slept curled in a ball The dog chased after the airplane The cat slept lazily
Why and how would you use this function? I have built this function to condense my list of UserAgents in my generator function.
This is also closely related to my content spinner function.

