数组中的变量(php)

时间:2016-05-07 13:12:55

标签: php wordpress

我需要在游戏中添加随机描述。游戏说明必须包含像这样的游戏标题

'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>';
    }

我不发布数据库更新代码,因为它工作) 那么,如何在描述中添加游戏标题?

1 个答案:

答案 0 :(得分:1)

使用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;
}