PHP数组打印

h5qlskok  于 2023-02-28  发布在  PHP
关注(0)|答案(2)|浏览(116)

我有一些来自MySQL数据库的字符串。其中两个用于这个问题:

$preset = "Because we to and "
$response = "want survive prosper improve"
$order = "00101101"

我想按照$order(0 =预设,1 =响应)的布局顺序在页面上打印预设和响应文本。
到目前为止,我有这个代码:

#Variables
$responsewords = explode(" ",$response);
$presetwords = explode(" ", $preset);
$orderexplode = str_split($order, 1);
#Doing Things
foreach($orderexplode as $o)
{
    for ($rsw = 0; $rsw <= $noresponse; $rsw++ )
    {
        switch ($o)
        {
            case 0:
                echo "<br>"."<label>".
                    $presetwords[$rsw].
                    "</label>"." ";
                break;
            case 1:
                echo "<input type='text' class='form-control'".
                    " placeholder=".$responsewords[$rsw].">";
                break;
        }
    }
}

我的问题是这段代码打印this,基本上它打印出整个字符串,但没有为每个0或1分成单独的单词。我寻找的结果是this(请原谅我的检查元素)。

9w11ddsr

9w11ddsr1#

试试看

$preset = "Because we to and ";
 $response = "want survive prosper improve";
 $order = "00101101";
$orderexplode = str_split($order, 1);
 $responsewords = explode(" ",$response);
    $presetwords = explode(" ", $preset);

$i =0; $k=0;
foreach($orderexplode as $o)
        {

            switch ($o) 
             {
                case 0:
                    echo "<label>".$presetwords[$i]."</label>"." ";
                    $i++;
                break;
                case 1:
                    echo "<input type='text' class='form-control' placeholder=".$responsewords[$k]."><br>";
                    $k++;
                break;
             }

        }
3htmauhk

3htmauhk2#

使用array_shift()sprintf可以缩短代码。
第一部分原封不动:

$preset        = "Because we to and ";
$response      = "want survive prosper improve";
$order         = "00101101";

然后,我们创建一个数组,在索引0处使用爆炸式预设,在索引1处使用爆炸式响应。此外,我们创建一个数组,其格式(一种模板)的键与之前的数组相对应。%s将被替换为单个单词:

$strings = array( explode(" ",$preset), explode(" ", $response) );
$formats = array( '<label>%s</label>', '<input type="text" class="form-control" placeholder="%s">' );

$orderexplode = str_split( $order, 1 );

通过一个foreach循环,我们根据$orderexplode$string子数组中提取单字,然后以sprintf()输出:

foreach( $orderexplode as $key => $o )
{
    $txt = array_shift( $strings[$o] );
    echo sprintf( $formats[$o], $txt ).PHP_EOL;
}

相关问题