如何列出从数据库检索的序列化数据。我的代码失败。
PHP 5.6
我的数据
a:3:{i:0;a:4:{s:2:"no";i:2;s:4:"name";s:23:"file-417-1546062916.zip";s:4:"type";s:28:"application/x-zip-compressed";s:4:"size";i:31835501;}i:1;a:4:{s:2:"no";i:1;s:4:"name";s:23:"file-417-1546063067.zip";s:4:"type";s:28:"application/x-zip-compressed";s:4:"size";i:31835501;}i:2;a:4:{s:2:"no";i:3;s:4:"name";s:23:"file-417-1546063154.zip";s:4:"type";s:28:"application/x-zip-compressed";s:4:"size";i:31835501;}}
我的代码
$fileStr = $getMeta('post_files', $pID);
$list = ($fileStr) ? unserialize($fileStr) : '';
foreach ($list as $k => $v) {
echo $k.' - '.$v;
}
注意:.......中的数组到字符串的转换。 0-数组
答案 0 :(得分:1)
您有一个多维数组,这意味着您需要两个foreach嵌套。
$str = 'a:3:{i:0;a:4:{s:2:"no";i:2;s:4:"name";s:23:"file-417-1546062916.zip";s:4:"type";s:28:"application/x-zip-compressed";s:4:"size";i:31835501;}i:1;a:4:{s:2:"no";i:1;s:4:"name";s:23:"file-417-1546063067.zip";s:4:"type";s:28:"application/x-zip-compressed";s:4:"size";i:31835501;}i:2;a:4:{s:2:"no";i:3;s:4:"name";s:23:"file-417-1546063154.zip";s:4:"type";s:28:"application/x-zip-compressed";s:4:"size";i:31835501;}}';
$list = unserialize($str);
if(!empty($list)){ // check if the array/string is empty
foreach ($list as $k => $v) {
echo $k . "\n";
foreach($v as $k2 => $val){
echo $k2.' - '.$val . "\n";
}
echo "\n\n";
}
}
输出:
0
no - 2
name - file-417-1546062916.zip
type - application/x-zip-compressed
size - 31835501
1
no - 1
name - file-417-1546063067.zip
type - application/x-zip-compressed
size - 31835501
2
no - 3
name - file-417-1546063154.zip
type - application/x-zip-compressed
size - 31835501
要查看数组的外观,可以使用print_r / var_dump或var_export。
它们将显示您的数组有多少层,如果数量未知,则可以使用array_walk_recursive遍历数组。