Jump to content

Multi-Dimensional Arrays. [Advanced Question]


ErikL

Recommended Posts

Hello, here is the PHP situation I'm in. I'll type it out in pseudo-ish code first.

<?php
            $multi_array = array(
                 array("cats", "dogs", "sheep", "walruses"),
                 array("jazz", "larva", "pencils", "derp"),
                 array("to", "much")
            );
            $string = array("the", "cats", "ate", "too", "many", "pencils");
            $count = count($string);
            for($i = 0; $i < $count; ++$i) {
                  if($string[$i] IN ARRAY $multi_array) {
                            THEN replace $string[$i] with a random word in the sub array of the multi-array
                             for example, if $string[$i] is cat, then it would replace it with any of the words in the sub array of multi-array, so it could be "cats", "dogs", "sheep", or "walruses"
                  }
           }
?>

 

 

I have no idea how to do this and tried thinking of ways for an hour and a half.  :-[

Certainly, I have a multi-dimensional array and a normal array.

 

I want to loop threw the array and if the normal array has any elements that are equal to any elements of the multi-dimensional array, then replace it with a random element of the sub array of the multi-dimensional array.

 

I hope that clarifies a few things.

One question, if the element that is being compared matches an element in the multi-dimensional array, where does the replacement element come from? Any one of the sub-arrays or the sub-array which contains the match?

 

Ken

One question, if the element that is being compared matches an element in the multi-dimensional array, where does the replacement element come from? Any one of the sub-arrays or the sub-array which contains the match?

 

Ken

 

The replacement would come from the array of which the key matched (randomly).

 

for example if the multi-array is: array("chocolate", "cinnamon", "strudels");

and the thing being compared is "chocolate" then "chocolate" could be replaced with "cinnamon", "strudels", or "chocolate"

try

<?php
$multi_array = array(
                 array("cats", "dogs", "sheep", "walruses"),
                 array("jazz", "larva", "pencils", "derp"),
                 array("to", "much")
            );
$string = array("the", "cats", "ate", "too", "many", "pencils");
$count = count($string);
foreach($string as $i => $word) {
    foreach ($multi_array as $ar){
        if(in_array($word, $ar)){
            $string[$i] = $ar[array_rand($ar)];
            break;
        }
    }
}
print_r($string);
?>

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.