DobotJr
DobotJr

Reputation: 4049

Breaking up a string into an array, PHP

I have a string that looks like this:

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

My goal, is to break this string up into an array. I think I'm close, but can't quite figure it out. I want my array structure to look like this:

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

This is what I have so far, but it's not working.

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

Upvotes: 1

Views: 77

Answers (2)

Manigandan Arjunan
Manigandan Arjunan

Reputation: 2265

<?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

Upvotes: 0

Achrome
Achrome

Reputation: 7821

Think of it as crumbling a cookie. Break it into progressively smaller pieces and process each piece accordingly.

Something like this should work

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

Here's a fiddle

Upvotes: 3

Related Questions