如何解析mysql表中的列,如<14-abc>;<8-def>;
作为:
abc =14
def = 8
abc存储值14,def存储值8并且具有多个条目。
因此,需要像数组或列表一样存储,以便能够访问和稍后处理解析的数据。
我不知道有任何解析器支持这种语法,所以你可以为一些琐碎的事情编写自己的解析器。以下是一个未经测试的示例:
$row = ' <14-abc>;<8-def>; ';
$output = Array();
$entries = explode(';', $row); //Split the row by every ';' delimiter
foreach ($entries as $item) { //For each entries
if (!empty($item)) { //Make sure the item isn't empty (last entry might be)
$item = str_replace(' ','',$item); //Remove useless char
$item = str_replace('<','',$item); //Remove useless char
$item = str_replace('>','',$item); //Remove useless char
$params = explode('-', $item); //Again, subsplit the key and the value from the item
$output[$params[1]] = $params[0]; //Push them into an array
}
}
然后你可以像这样使用你的真棒阵列:
foreach ($output as $key=>$value) {
echo $key.'='.$value;
}
输入是$row
字符串,输出是$output
数组。你甚至可以把它包装成一个函数;)
?php
function parser($row)
{
$output = Array();
$entries = explode(';', $row); //Split the row by every ';' delimiter
foreach ($entries as $item) { //For each entries
if (!empty($item)) { //Make sure the item isn't empty (last entry might be)
$item = str_replace(' ','',$item); //Remove extra char
$item = str_replace('<','',$item); //Remove extra char
$item = str_replace('>','',$item); //Remove extra char
$params = explode('-', $item); //Again, subsplit the key and the value from the item
$output[$params[1]] = $params[0]; //Push them into an array
}
}
foreach ($output as $key=>$value) {
$sql1 = "INSERT INTO `tablename`(`column name`, `column name`) VALUES ('$key','$value')";
mysql_query($sql1);
}
}
?>
这完成了所有的工作。。定义解析器函数,解析数据并将结果插入DB