2016-03-19 58 views
1

阵列我有数据的字符串列表,像这样:字符串以相同的顺序PHP

Category(1,2,"some text"); 
post(111,233,"post"); 
post(111,233,"post"); 
post(111,233,"post"); 
Category(1,2,"some text"); 
post(111,233,"post"); 
post(111,233,"post"); 
post(111,233,"post"); 
post(111,233,"post"); 
post(111,233,"post"); 

我需要将其转换为数组中的顺序相同,一些这样的事,例如:

Array 
(
[0] => Array 
    (
     ['category'] => Category(1,2,"some text") 
     ['posts'] => Array 
       (
        [0] => post(111,233,"post") 
        [1] => post(111,233,"post") 
        [2] => post(111,233,"post") 
       ) 
    ) 
[2] => Array 
    (
     ['category'] => Category(1,2,"some text") 
     ['posts'] => Array 
       (
        [0] => post(111,233,"post") 
        [1] => post(111,233,"post") 
        [2] => post(111,233,"post") 
        [3] => post(111,233,"post") 
        [4] => post(111,233,"post") 
       ) 
    ) 
) 

我能得到分类阵列单独和岗位阵列独自一人,但我怎样才能把它们放在一起在一个阵列中以相同的顺序..

preg_match_all("/(category)\(+(.*?)\)/",$string,$cats , PREG_SET_ORDER); 
preg_match_all("/(post)\(+(.*?)\)/",$string,$posts , PREG_SET_ORDER); 

print_r($cats); 
print_r($posts); 

谢谢

回答

0

您可以将标记化字符串,然后通过一个分析每个项目一个,比如这个:

$result = array(); 
$token_list = explode(";\n",$string); 
$category_counter = -1;//index trick for the first occorrence of Category 

foreach($token_list as $token){ 
    if(substr($token,0,8) == "Category"){ 
    $category_counter++; 
    $result[$category_counter]["category"] = $token; 
    }else{ 
    $result[$category_counter]["posts"][] = $token; 
    } 
} 
+0

谢谢乔瓦尼,几乎没有,我认为唯一的问题是,我不能让SUBSTR ($ token,0,1)的权利,它不会返回“类别”,当我手动尝试它,它返回“1”!我试图找出问题是什么,感谢很多 – Ahmad

+0

遗憾,它重新调整 “类别”,但条件从不工作,我喜欢的数组: 类别阵列 ( [-1] =>数组 ( [交] =>数组 ( =>类别(1,2,“一些文本”) [1] =>帖子(111,233,“帖子”) [2] =>帖子(111,233,“帖子”) = >类别(1,2,“some text”) [4] =>帖子(111,233,“帖子”) [5] =>帖子(111,233,“帖子”) [6] =>帖子(111,233, “post”) – Ahmad

+0

你的字符串是这样的,我的意思是在分号后面有相同的大小写敏感和新行? ' $ string ='Category(1,2,“some text”); (111,233,“post”); (111,233,“post”); (111,233,“post”); 类别(1,2,“some text”); (111,233,“post”); (111,233,“post”); (111,233,“post”); (111,233,“post”); (111,233,“post”);'; ' –

相关问题