我正在运行 SQL 查询来输出字段值,该字段具有值数组。如何使用 php/css/html 格式化这些值。
这是我从以下代码获得的输出:
$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/> ";
}
MySQL 输出值:
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";}
}
期望的输出:
FirstName LastName
testb1 test1
testb2 test2
有人可以帮我解决这个问题吗?
最佳答案
首先,您需要从序列化数据中删除新行和制表符,然后才能正确 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;
}
First Name Last Name
testb1 test1
testb2 test2
您可以将 "\t"
制表符替换为您想要用来分隔列的任何字符,并将 PHP_EOL
替换为用于分隔新行的字符。
如果您想将此数据添加到数组中(例如写入 CSV),则只需使用 $output[] = implode...
而不是 echo
并在末尾使用 $output
。
关于php - 格式化 mysql 的输出(值数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29834586/