数组中的变量(php)


variable in array (php)

我需要为游戏添加随机描述。游戏描述必须包含类似的游戏标题

'1' => 'some text1 (game_title) some text'

之后,新的描述发送到数据库。这是我的密码。

        $game_descr = array('1' => 'some text1 (post_title) some text' ,
                        '2' => 'some text2 (post_title) some text' ,
                        '3' => 'some text3 (post_title) some text' ,
                        '4' => 'some text4 (post_title) some text' ,
                        '5' => 'some text5 (post_title) some text' ,
                        '6' => 'some text6 (post_title) some text' ,
                        '7' => 'some text7 (post_title) some text' ,
                        '8' => 'some text8 (post_title) some text' ,
                        '9' => 'some text9 (post_title) some text' ,
    );

    $newtable = $wpdb->get_results("SELECT ID, post_title, post_content FROM wp_posts WHERE post_status = 'publish'");
    foreach ($newtable as $gametable) {
            foreach ($game_descr as $i => $value) {
                $rand_value = rand(1,9);
            }
    echo '<div class="game_descr"><textarea name="game_descr">'.$game_descr[$rand_value].'<br />'.$gametable->post_content.'</textarea></div>';
    }

我不公开数据库更新代码,因为它有效)那么,如何将游戏标题添加到描述中呢?

使用sprintf,使用%s作为占位符:

$game_descr = [
  1 => 'some text1 (%s) some text',
  // ...
];
$posts = $wpdb->get_results("SELECT ID, post_title, post_content
  FROM wp_posts WHERE post_status = 'publish'");
foreach ($posts as $p) {
  $index = mt_rand(1, count($game_descr));
  $descr = sprintf($game_descr[$index], $p->post_content);
  echo <<<EOS
<div class="game_descr">
  <textarea name="game_descr">{$descr}<br/>
  {$p->post_content}
  </textarea>
</div>;
EOS;
}