0

このコードの何が問題なのか理解できません。ショートコードを置き換えるだけで{info}、他はすべてそのままにします。

コードは次のとおりです。

class Compliment_Gen {

  public $madlib; 
  public $madlib_answers;
  public $madlib_line;
  public $new_compliment;

  //Sets up 'Madlibs' Arrays
  public function __construct()
  {
    $this->madlib = array("{great} {post}!", "{great} {post}! {thanks}!", 
                           "{great} {post}! {thanks} for this {info}!", 
                           "{great} {post}!, I've been looking for this {info}. {thanks}!", 
                           "{great} {info}.", "{great} {info}. {thanks}!", 
                           "I've been {looking for} this {info} for quite some time.", 
                           "{thanks} for this!", "{thanks} for this {great} {post}!"
                          );

    $this->madlib_answers = array('good job' => array ("good job", "nice work", "nicely done!", "excellent work!", "great job!"),
                         'post' => array ( "post", "article", "write up", "blog post", "piece"),
                         'great' => array ( "great", "amazing", "fantastic", "excellent", "solid" ),
                         'thanks' => array ( "thanks", "thank you", "thanks so much", "thank you so much"),
                         'looking for' => array ( "looking for", "looking everywhere for", 
                                                 "searching for", "searching everywhere for", "hoping for", "hoping to find"),
                         'info' => array ( "info", "information")
                         );

    $this->compliment_gen($this->madlib, $this->madlib_answers);
  }

  //One Random Compliment Produced
  public function compliment_gen($madlib, $madlib_answers)
  {
    $this->madlib_line = $this->madlib[rand(0, count($this->madlib)-1)];
    foreach( $madlib_answers as $seed => $spins)
    {
        $this->new_compliment = str_replace("{" . $seed . "}", $spins[ rand(0, count($spins)-1)], $this->madlib_line );
    }

    echo $this->new_compliment;
  }
}

どうしたの?

4

1 に答える 1

1

次のようにしてみてください。str_replace文字列が置き換えられるため、新しい値を置き換えるために値を置き換える必要があるたびに。現在のコードと同様に、実際のステートメントを何度も置き換えています

$this->madlib_line = $this->madlib[rand(0, count($this->madlib)-1)];
$this->new_compliment = $this->madlib_line;

foreach( $madlib_answers as $seed => $spins)
    {
        $this->new_compliment = str_replace("{" . $seed . "}", $spins[ rand(0, count($spins)-1)], $this->new_compliment );
    }
于 2012-11-25T10:55:00.337 に答える