【问题标题】:Update Header String when looping through an array循环遍历数组时更新标题字符串
【发布时间】:2019-08-03 06:19:24
【问题描述】:

背景:我正在循环访问数据库数据并将其输出到表格中的页面。我的循环首先输出标题信息,但标题是我所说的未准备好前端。

例如: child_0_birthday 需要更改为 Child 1 Birthday。

到目前为止,我所拥有的如下:

    //Define table header section here
        foreach ($fields as $k => $v){
        $html .= '<th class="manage-column" data-key="'.esc_html($v).'">'.updateHeaderName(vsz_cf7_admin_get_field_name($v)) .'</th>';
                                    }

    //This function would do the clean up

    $devHeaderNames = array("child_0_birthday", "child_0_fname", "child_0_lname", "child_0_age");

function updateHeaderName($oldHeader) {

    if (in_array($oldHeader, $devHeaderNames))
      {
     //This is where I would want to change the value of $oldHeader to something cleaner and spit it back out. I could write a very long if statement but there has to be a better way. 
        if ($oldHeader == child_0_fname){
            $newHeader = "Child 1 First Name";
            return $newHeader;
        }else if...
      }
   }

问题:有没有比编写一个很长的 if 语句来更改每列标题中显示的字符串更有效的方法?

【问题讨论】:

  • 创建一个替换数组然后php.net/manual/en/function.str-replace.php
  • 字符串替换应该有效。或者,您可以在 _ 上展开您的变量名,并创建一个查找表,将后端变量名替换为更用户友好的变量名。

标签: php arrays loops replace


【解决方案1】:

您可以只使用您的数组来转换关联的键和值。假设$header = "child_0_birthday"

$devHeaderNames = array("child_0_birthday" => "Child 1 Birthday"); //etc...

if(isset($devHeaderNames[$header])) {
    $header = $devHeaderNames[$header];
}

【讨论】:

  • 我知道会有更简单的方法。感谢@AbraCadaver,这是有道理的。
猜你喜欢
  • 2023-03-23
  • 2017-10-06
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 2022-01-16
  • 2019-09-07
相关资源
最近更新 更多