格式化mysql的输出(值数组)

时间:2015-04-23 21:24:23

标签: php html mysql

我正在运行一个sql查询来输出字段的值,该字段具有值数组。如何使用php / css / html格式化这些值。

这是我从以下代码获得的输出:

select T1.section_id,
       T1.section_name,
       T1.subjects_count,
       T2.batch_count
FROM (
select S.section_id, 
       S.section_name,
       COUNT(SS.subject_id) as subjects_count
from Section S
LEFT JOIN Section_Subject SS
on S.section_id = SS.section_id
group by S.section_id, S.section_name )T1
LEFT JOIN (
select S.section_id, 
       S.section_name,
       COUNT(SB.batch_id ) as batch_count
from Section S
LEFT JOIN Section_Batch SB
on S.section_id = SB.section_id
group by S.section_id, S.section_name
  ) T2
 on T1.section_id = T2.section_id

MySQL输出值:

$rb = $wpdb->get_results("select value 
                          from wp_rg_lead_detail 
                          where field_number = 33 
                            and lead_id = 
                                 (select distinct lead_id 
                                  from wp_rg_lead_detail 
                                  where value = '".$uname."')
                         "); 
foreach( $rb as $r){ 
    echo $r->value . "<br/> "; 
}

期望的输出:

a:2:{
    i:0;a:2:{s:10:"First Name";s:6:"testb1";s:9:"Last Name";s:5:"test1";}
    i:1;a:2:{s:10:"First Name";s:6:"testb2";s:9:"Last Name";s:5:"test2";}
    }

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

首先,您需要先删除序列化数据中的新行和标签,然后才能正确unserialize()

$data = unserialize('a:2:{i:0;a:2:{s:10:"First Name";s:6:"testb1";s:9:"Last Name";s:5:"test1";}i:1;a:2:{s:10:"First Name";s:6:"testb2";s:9:"Last Name";s:5:"test2";}}');

您可以使用这样的简单循环输出所需的结果:

// Keep track of whether the headers have been output yet
$headersOutput = false;
foreach ($data as $row) {
    // If the headers haven't been output yet
    if (!$headersOutput) {
        // Output the headers only
        echo implode("\t", array_keys($row)), PHP_EOL;
        // Update variable so it won't happen again
        $headersOutput = true;
    }
    // Output the values
    echo implode("\t", array_values($row)), PHP_EOL;
}

Example:

First Name  Last Name
testb1  test1
testb2  test2

您可以将"\t"制表符替换为要分隔列的任何字符,并交换PHP_EOL以分隔新行。

如果要将此数据添加到数组(例如,要写入CSV),请使用$output[] = implode...代替echo,最后使用$output