自定义PHP字符串格式

时间:2012-06-10 06:36:11

标签: php arrays string loops foreach

我有一个包含20组字段的HTML表单。这里有两个例子:

<input type="text" class="auto-clear" id="p1weight" name="p1weight" value=""  />     
<input type="text" class="auto-clear" id="p1length" name="p1length" value="" />     
<input type="text" class="auto-clear" id="p1width" name="p1width" value="" />    
<input type="text" class="auto-clear" id="p1height" name="p1height" value="" />    

<input type="text" class="auto-clear" id="p2weight" name="p2weight" value="" />    
<input type="text" class="auto-clear" id="p2length" name="p2length"  value="" />     
<input type="text" class="auto-clear" id="p2width" name="p2width" value="" />    
<input type="text" class="auto-clear" id="p2height" name="p2height" value="" /> 

我使用以下PHP代码生成一个字符串( $ all )来存储字段值:

foreach( range( 1, 20) as $i)
    {
        // Create an array that stores all of the values for the current number
        $values = array( 
            'p' . $i . 'weight' => $_POST['p' . $i . 'weight'],
            'p' . $i . 'length' => $_POST['p' . $i . 'length'], 
            'p' . $i . 'width' => $_POST['p' . $i . 'width'], 
            'p' . $i . 'height' => $_POST['p' . $i . 'height'] 
        );

        $all .= implode( '|', $values) . "\n\n";
    }

如果我对2组字段的输入是1,2,3和1; 4,这使我的 $ all 值为:1|2|3|4 1|2|3|4

但是,我想更多地定制这个。最终,我希望 $ all 为:

Item1: Weight (kg):1 Length (cm): 2 Width (cm): 3 Height (cm): 4
Item2: Weight (kg):1 Length (cm): 2 Width (cm): 3 Height (cm): 4

如何更新上面的PHP以实现此目的?

非常感谢任何指示。

2 个答案:

答案 0 :(得分:1)

上面的代码已经非常精细,可以将提交的数据规范化为数组。要现在映射数组中的值,您可以使用名为vsprintf的函数。它需要两个参数。第一个是格式化字符串,您可以在其中添加占位符以标记值的格式(例如%d以显示为整数(d =数字)),第二个参数是包含值的数组:< / p>

$format = "Item$i: Weight (kg): %d length (cm): %d Width (cm): %d Height (cm): %d \n\n";
$all .= vsprintf($format, $values);

此方法的好处是您可以解耦值提取和格式化。然后,您可以在将来将这两个部分彼此远离,例如多种类型的输出。

此外,这保留了您已经写好的内容,这是规范化提交数据的一大进步。

答案 1 :(得分:0)

foreach( range( 1, 20) as $i)
        {

            $all .= "Item".$i.": Weight (kg):".$_POST['p' . $i . 'weight']." Length (cm): ".$_POST['p' . $i . 'length']." Width (cm): ".$_POST['p' . $i . 'width']." Height (cm): ".$_POST['p' . $i . 'height']."\n";
        }