phparraysmultidimensional-arraysplit

Explode string with two different separators to create an array or indexed arrays


I have a string:

01;Tommy;32;Coder&&02;Annie;20;Seller

I want it like this:

array (size=2)
0 => 
array (size=4)

  0 => string '01' (length=2)

  1 => string 'Tommy' (length=5)

  2 => int 42

  3 => string 'Coder' (length=5)  

1 => 
array (size=4)

  0 => string '02' (length=2)

  1 => string 'Annie' (length=5)

  2 => int 20

  3 => string 'Seller' (length=6)

Solution

  • Not sure if the datatypes will be matching (as I believe it's all in a string) but here's the code

     $myarray = array();
     foreach(explode("&&",$mystring) as $key=>$val)
     {
     $myarray[] = explode(";",$val);
     }
    

    The explode command takes a string and turns it into an array based on a certain 'split key' which is && in your case
    but since this is a dual array, I had to pass it through a foreach and another explode to solve.