字符串到数组的顺序与PHP

时间:2016-03-19 16:05:33

标签: php arrays

我有如下数据的字符串列表:

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")
                )
   )
)

我可以单独获取Categories数组并单独发布数组,但是如何将它们以相同的顺序放在一个数组中..

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

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

谢谢

1 个答案:

答案 0 :(得分: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;
  }
}