字符串到数组的顺序与 PHP 相同


string to array in the same order 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);

谢谢

您可以标记字符串,然后逐个解析每个项目,如下所示:

$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;
  }
}