如何以人类可读的格式显示数组?

3 php arrays formatting

如果我有一个如下所示的数组:

$str = '';
if( $_POST['first'] )
    $str = $_POST['first'];
if( $_POST['second'] )
    $str .= ($str != '' ? ',' : '') . $_POST['second'];
if( $_POST['third'] )
    $str .= ($str != '' ? ',' : '') . $_POST['third'];
if( $_POST['fourth'] )
    $str .= ($str != '' ? ',' : '') . $_POST['second'];
$str .= ($str != '' ? '.' : '');
Run Code Online (Sandbox Code Playgroud)

这给了我这样的东西:

乔,亚当,迈克.

但是,我想在最后一项之前加上" ".

那么它会读到:

乔,亚当迈克.

如何修改我的代码才能执行此操作?

raz*_*zed 10

数组非常棒:

$str = array();
foreach (array('first','second','third','fourth') as $k) {
    if (isset($_POST[$k]) && $_POST[$k]) {
        $str[] = $_POST[$k];
    }
}
$last = array_pop($str);
echo implode(", ", $str) . " and " . $last;
Run Code Online (Sandbox Code Playgroud)

当有一个项目时,您应该特别注意上述情况.事实上,我写了一个名为"连接"的函数来完成上述操作,并包括特殊情况:

function conjunction($x, $c="or")
{
    if (count($x) <= 1) {
        return implode("", $x);
    }
    $ll = array_pop($x);
    return implode(", ", $x) . " $c $ll";
}
Run Code Online (Sandbox Code Playgroud)

好问题!

更新:执行此操作的通用方法:

function and_form_fields($fields)
{
     $str = array();
     foreach ($fields as $k) {
         if (array_key_exists($k, $_POST) && $v = trim($_POST[$k])) {
              $str[] = $v;
         }
     }
     return conjunction($str, "and");
}

...

and_form_fields(array("Name_1","Name_2",...));
Run Code Online (Sandbox Code Playgroud)

我添加了正确的$ _POST检查以避免通知和空值.