Wordpress 如何将 user_meta 数组显示为 table?

Wordpress how to display user_meta array as a table?

我试过在 Wordpress Whosebug 上发布这个,但没有得到任何答案。

这是 PHP + Wordpress 问题,也许这里有人可以提供帮助。

好的,所以我正在为使用 user_meta 数组的用户构建一个“交易”table。

我是新手,正在尝试解决问题。

基本上,在实践中我知道如何将数组存储到 user_meta

$the_meta_array = array (
    'type' => 'value-1',
    'amount' => 'value-2',
    'date' => 'value-3',
    'method' => 'value-4',
    'status' => 'value-5',
);  
$user_id = 12345;  
$user_meta_key = 'transactions';  
add_user_meta( $user_id, $user_meta_key, $the_meta_array );

我的问题是如何以 table 格式为该特定用户显示 'transactions' meta_key,如下所示:

-----------------------------------------------------
type    | amount  | date          | method | status
-----------------------------------------------------
deposit |      | 2021,09,18    | Paypal | done
-----------------------------------------------------
deposit |      | 2021,09,14    | Paypal | done
-----------------------------------------------------
cashout |      | 2021,09,11    | Paypal | done

是否可以将 meta_key 数组显示为循环?

不知道实际操作如何。

我知道这应该是可能的。

如有任何帮助,我们将不胜感激。

1- 使用 get_users 函数获取所有用户:

$args = array(
  'fields' => array('ID')
);
$users = get_users($args);

2-为有交易数据的用户创建一个空数组:

$users_with_transaction = array();

3- 遍历所有用户并挑选出具有交易数据的用户,然后使用 array_push 填充 $users_with_transaction 数组:

foreach ($users as $user) {
  $users_transaction = (get_user_meta($user->ID, 'transactions'));
  if ($users_transaction) {
    array_push($users_with_transaction, $users_transaction);
  }
}

4- 创建您的 table 结构并通过遍历 $users_with_transaction 数组来填充它:

<table>
  <thead>
    <tr>
      <td>type</td>
      <td>amount</td>
      <td>date</td>
      <td>method</td>
      <td>status</td>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($users_with_transaction as $user_data) { ?>
      <tr>
        <?php foreach ($user_data[0] as $data_key => $data_value) { ?>
          <td><?php echo $data_value; ?></td>
        <?php } ?>
      </tr>
    <?php } ?>
  </tbody>
</table>

这将输出:

然后您可以使用 css 来设计您的 table。

这是一个 table 结构的例子,内联 css 给你的 table 行边框:

<table style='border-collapse:collapse'>
  <thead>
    <tr>
      <td style="border: 1px solid black;">type</td>
      <td style="border: 1px solid black;">amount</td>
      <td style="border: 1px solid black;">date</td>
      <td style="border: 1px solid black;">method</td>
      <td style="border: 1px solid black;">status</td>
    </tr>
  </thead>
  <tbody>
    <?php
    foreach ($users_with_transaction as $user_data) { ?>
      <tr>
        <?php
        foreach ($user_data[0] as $data_key => $data_value) {
        ?>

          <td style="border: 1px solid black;"><?php echo $data_value; ?></td>
        <?php
        } ?>
      </tr>
    <?php
    }
    ?>
  </tbody>
</table>

这将输出: