解析字符串,并将其存储到数据库

问题描述:

继续this question解析字符串,并将其存储到数据库

我有这个字符串:

$table_summary = ' 
    [Category Name 1=>Title x:Description y,Title q:Description n,Title r:Description m,] 

    !£|£! 

    [Category Name 2=>Title z:Description a,Title j:Description k,Title p:Description f,] 

    !£|£! 
'; 

正如你看到的,有字符串作为!£|£!在分离,我有2个表:

products_spec_subjects 
id  product_id  val 

products_spec_details 
id  title  description subject_id 

我想存储提到的字符串到这些表中,而category name将存储到第一个表中,它的详细信息如标题和des cription将存储在第二个表中,并将使用subject_id作为外键链接到第一个表。

这样毕竟提到的字符串应该被存储到数据库像(e.x $product_id=12):

products_spec_subjects 
1  12  Category Name 1 
2  12  Category Name 2 


products_spec_details 
1 Title x  Description y  1 
2 Title q  Description n  1 
3 Title r  Description m  1 
4 Title z  Description a  2 
5 Title j  Description k  2 
6 Title p  Description f  2 

这是迄今为止我残缺码:

$technical_specifications_arr = explode('!£|£!', $table_summary); 
     unset($technical_specifications_arr[count($technical_specifications_arr) - 1]); 
     foreach($technical_specifications_arr as $main_value){ 
      $i = 0; 
      $this_arr = explode('=>', $main_value); 
      foreach($this_arr as $value){ 
       $cat_name = substr($this_arr[0], 1); 
       $details = substr($this_arr[1], 0, -1); 
        if($i == 0){ 
        $tech_main_insert = mysql_query("INSERT INTO products_spec_subjects (product_id, val) VALUES ('$product_id', '$cat_name')") or die(mysql_error()); 
        $this_main_id = mysql_insert_id($link); 
        } 
       $i++; 
       $another_arr = explode(',', $details); 
       unset($another_arr[count($another_arr) - 1]); 
       foreach($another_arr as $another_val){ 

        $final = explode(':', $another_val); 
        foreach($final as $final_value){ 
         // now I can't separate the titles and description here 
        } 
       } 
      } 
     } 

我感谢所有帮助。

+0

代码的输出是什么?即当你回显'$ final_value'时你会得到什么? – verbumSapienti

+0

一些f ***编辑了字符串,这实际上与我所需要的无关!在最后一个foreach之前:'foreach($ another_arr as $ another_val){'一切正常,它插入主要猫好 – behz4d

+0

我不确定为什么你需要在你的代码中使用'unset()',也许他们是问题 – verbumSapienti

您不需要迭代$ final循环。只需将您的值提取出来:

  foreach($another_arr as $another_val){ 
       $final = explode(':', $another_val);      
       // $final[0] = title 
       // $final[1] = desc 
       echo $final[0].' - '.$final[1]."<br />\n"; 
      } 
+0

这里有一个问题,它会回应两次这个应该打印,因为它也在*foreach中间 – behz4d

+0

我只需要'如果$ i == 1'回声...,谢谢 – behz4d