拆分字符串并存储在php中的单独变量中

时间:2014-04-11 04:20:32

标签: php arrays

我在尝试字符串address:message:ID|address:message:ID|address:message:ID|address:message:ID|address:message:ID|address:message:ID

后尝试拆分
$a[1] =     address:message:ID
$a[2] =     address:message:ID
$a[3] =   address:message:ID
$a[4] =   address:message:ID
$a[5] =    address:message:ID
$a[6] =    address:message:ID

我想再次分裂上面的字符串我试图分成以下

$a[1][1] = address 
$a[1][2] = message
$a[1][3] = ID

如何在不失去代码执行速度的情况下执行此操作。

2 个答案:

答案 0 :(得分:2)

使用foreach并使用|作为分隔符遍历展开的字符串,使用explode()作为分隔符将这些展开的值传递给另一个:并推送它们使用$new_arr

在新数组array_push
<?php
$str='address:message:ID|address:message:ID|address:message:ID|address:message:ID|address:message:ID|address:message:ID';
$new_arr=array();
foreach(explode('|',$str) as $k=>$v)
{
  array_push($new_arr,explode(':',$v));
}
print_r($new_arr);

Working Demo

答案 1 :(得分:0)

使用Explodeforeach

这样做
<?php
      $str='address:message:ID|address:message:ID|address:message:ID|address:message:ID|address:message:ID|address:message:ID';
$arr=explode('|',$str);
foreach($arr as $v){
 $a[]=explode(':',$v);
        }
 print_r($a);

Demo

<强>输出

Array
(
    [0] => Array
        (
            [0] => address
            [1] => message
            [2] => ID
        )

    [1] => Array
        (
            [0] => address
            [1] => message
            [2] => ID
        )

    [2] => Array
        (
            [0] => address
            [1] => message
            [2] => ID
        )

    [3] => Array
        (
            [0] => address
            [1] => message
            [2] => ID
        )

    [4] => Array
        (
            [0] => address
            [1] => message
            [2] => ID
        )

    [5] => Array
        (
            [0] => address
            [1] => message
            [2] => ID
        )

)