【问题标题】:php arrays: how to print only array values but not keysphp数组:如何只打印数组值而不是键
【发布时间】:2011-03-23 10:00:12
【问题描述】:

此代码循环通过一个 mysql 表并打印出空/空字段。但是它会像这样打印数组值和键

Array ( 
    [0] => Field "dob" on entry "1" is empty/null 
    [1] => Field "user_name" on entry "7" is empty/null
)

我如何打印这样的field "dob" on entry "1" is empty/null

$sql = "SELECT * FROM userinfo";
$res = mysql_query($sql);
while ($row = mysql_fetch_array($res)) {
    foreach($row as $key => $field) {
        if(empty($field)) {
            $emptyFields[] = sprintf('Field "%s" on entry "%d" is empty/null', $key,   $row['userid']);
         }
     }
}
print_r($emptyFields);

【问题讨论】:

  • @Belinda:感谢编辑

标签: php arrays arraylist


【解决方案1】:
echo implode('<br>', $emptyFields);

【讨论】:

  • 效果很好。它打印出条目“11”上的字段“4”为空/null 条目“11”上的字段“地址”为空/null。他们都是一样的。如何避免在条目“11”上打印字段“4”为空/null。
  • 我不明白你需要什么。你想跳过整数键,对吗?只需使用检查if( ! is_integer($key) AND empty($field))
  • 如何避免重复打印列标题?例如。 “2”列的“名称”字段为空,“3”列的“名称”字段为空。我只想打印一个字段“名称”并在单独的页面上提供详细信息。
【解决方案2】:

那是因为您使用 print_r 来输出该数组。所以输出的格式是人类可读的。 为了使它更漂亮,请尝试像以前使用该字段一样遍历它:

foreach($emptyFields as $key => $field) {
echo('Field "'.$field.'" on entry "'.$emptyField['userid'].'" is empty/null');
}

【讨论】:

    【解决方案3】:
    $sql = "SELECT * FROM userinfo";
    $res = mysql_query($sql);
    while ($row = mysql_fetch_array($res)) {
      foreach($row as $key => $field) {
        if(empty($field)) {
          $emptyFields[] = sprintf('Field "%s" on entry "%d" is empty/null', $key,  $row['userid']);
        }
      }
    }
    

    【讨论】:

      【解决方案4】:

      我不知道我是否理解正确,但我认为您的问题的解决方案是:

      将最后一行改为:

      $emptyFields[] = sprintf('Field "%s" on entry "%d" is empty/null', $field, $row['userid']);}}}print_r($emptyFields);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-23
        • 1970-01-01
        • 2021-11-29
        • 1970-01-01
        相关资源
        最近更新 更多