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

标签 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 != '' ? '.' : '');

这给了我这样的东西:

乔、亚当、迈克。

不过,我想在最后一项前加一个“and”。

然后它会读作:

乔、亚当、迈克。

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

最佳答案

数组在这方面很棒:

$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;

当只有一项时,您可能应该对上述情况进行特殊处理。事实上,我写了一个名为“conjunction”的函数来执行上述操作,并包括特殊情况:

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

好问题!

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

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",...));

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

关于php - 如何以人类可读的格式显示数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1010833/

相关文章:

php - 仅一个文件的 RewriteRule

C# 字符串格式标志或修饰符到小写参数

java - 根据 Java 中的表格分配成绩

c - 指向空数组的指针

git - 在一系列 git 提交上运行 git-clang-format

excel - (Excel) 基于相邻单元格值的条件格式

php - 从 mysql 到 php 获取值(value)时遇到麻烦

php - 尝试在 phpmyadmin 中设置外键

php - “列计数与第1行的值计数不匹配”

javascript - 将数组分割成 block