将 WordPress DB 查询中的元数据数组显示到 4 列的表中

问题描述 投票:0回答:1

我有一个变量(数组)并返回以下内容:

array(13) { 
    ["meta_id"]=> string(1) "2" 
    ["post_id"]=> string(4) "2112"
    ["provider"]=> string(12) "Abc news"
    ["scheme"]=> string(3) "morning"
    ["viewers"]=> string(9) "2000"
    ["min_time"]=> string(3) "5"
    ["max_time"]=> string(3) "100"
    ["bways"]=> string(2) "10"
    ["release_date"]=> string(10) "04-05-2021"
    ["type"]=> string(11) "Video"
    ["variance"]=> string(4) "4k"
    ["tech"]=> string(9) "JS, HTML5"
    ["game_id"]=> string(5) "17640" 
}

我从以下查询中获取此数据:

$meta = $wpdb->get_row( $wpdb->prepare("
    SELECT * FROM ".$table_name." WHERE post_id = %d
", $post_id), ARRAY_A);

目前,我正在使用类似以下方式输出表中的数据:

$output .="<tr>";
$output .= sprintf('<td>%s</td><td>%s</td>', $attribute, $value);
$output .="</tr>";

它正在生成一个包含 2 列的表格。我想要 4 列,如下图所示:

左列最多有 5 行,其余行位于另一列。

php arrays wordpress foreach html-table
1个回答
1
投票

基于此数据数组:

$meta = [
    "meta_id" => "2",
    "post_id" => "2112", 
    "provider" => "Abc news", 
    "scheme" => "morning", 
    "viewers" => "2000", 
    "min_time" =>  "5", 
    "max_time" =>  "100", 
    "bways" =>  "10", 
    "release_date" => "04-05-2021", 
    "type" => "Video", 
    "variance" => "4k", 
    "tech" => "JS, HTML5", 
    "game_id" => "17640", 
];

您可以使用“模”运算符来获取在 4 列表中分派的数据,例如:

$index = 0;
$count = count($meta);

$output = '<table>
<tr><th>Attribute</th><th>Value</th><th>Attribute</th><th>Value</th></tr>
<tr>';

// Loop through array keys / values
foreach ( $meta as $attribute => $value ) {
    $output .= sprintf('<td>%s</td><td>%s</td>', $attribute, $value);
    $output .= $index % 2 === 0 && ($count - 1) === $index ? '<td></td><td></td>' : '';
    $output .= $index % 2 === 1 ? '</tr><tr>' : '';

    $index++;
}
$output .= '</tr>
</table>';

它应该按预期工作。你会得到类似的东西:

© www.soinside.com 2019 - 2024. All rights reserved.