将字符串分解为数组,PHP

时间:2013-12-13 04:10:37

标签: php arrays loops

我有一个看起来像这样的字符串:

$dash_access = "1-10:rw,14:rw|10-10:ro,14:ro";

我的目标是将此字符串分解为数组。我想我已经接近了,但不能完全弄清楚。我希望我的数组结构如下所示:

$array = Array  
               (
               [1] => Array
                   (
                   [10] => rw
                   [14] => rw
                   )
               [10] => Array
                   (
                   [10] => ro
                   [14] => ro
                   )
               )

这是我到目前为止所做的,但它没有用。

 $dash_access_split = explode("|",$dash_access); 
 for ($a=0;$a<count($dash_access_split);$a++) {
  $split1 = explode("-", $dash_access_split[$a]);  
  $split2 = explode(",", $split1[1]);              
  for ($b=0;$b<count($split2);$b++) {             
   $split3 = explode(":", $split2[$b]);            
   $dash_access_array[$split1[0]][] = $split3[0];
   $dash_access_array[$split1[0]][] = $split3[1]; 
  }   
 }

2 个答案:

答案 0 :(得分:3)

将其视为摇摇欲坠的饼干。将其分解为逐渐变小的部分并相应地处理每个部分。

这样的事情应该有效

$dashAccess = "1-10:rw,14:rw|10-10:ro,14:ro";
$outArray = [];

foreach (explode('|', $dashAccess) as $bigPiece) {
    list($medKey, $medPiece) = explode('-', $bigPiece);
    $outArray[$medKey] = [];
    foreach (explode(',', $medPiece) as $smallPiece) {
        list($crumbleKey, $crumblePiece) = explode(':', $smallPiece);
        $outArray[$medKey][$crumbleKey] = $crumblePiece;
    }
}

var_dump($outArray);

这是fiddle

答案 1 :(得分:0)

<?php $dash_access = "1-10:rw,14:rw|10-10:ro,14:ro";
$big_array=explode('|',$dash_access);
$small_array=array();
foreach($big_array as $key=>$value)
{
    $small_array[]=explode('-',$value);
    foreach($small_array as $key => $value)
    {
        $chunk=explode(',',$value[1]);
        foreach($chunk as $value1)
        {
            $chunk_small=explode(':',$value1);
            $result[$value[0]][$chunk_small[0]]=$chunk_small[1];
        }
    }
}
print_r($result);

http://codepad.org/sKZyDu2m