0

suppose I have a string like the follwing:

   01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16 

How to convert it to a 2D array like the follwing using php?:

   01 03 02 15
   05 04 06 10 
   07 09 08 11  
   12 14 13 16 

any help will be greatly appreciated, thanks!

1

5 Answers 5

2

This should do the trick:

$tmp  = explode( '|', $str );
$data = array();

foreach ( $tmp as $k => $v )
{
  $data[] = explode( ',', $v );
}

explode() is your friend.

Sign up to request clarification or add additional context in comments.

Comments

1
$str = '01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16';
$arr = array_map(function($val) { return explode(',',$val); },explode('|',$str));

var_dump($arr);

PHP >= 5.3.0

Comments

1

Here's a quickie option, which requires PHP 5.3.0 or above (that you should be using anyway).

$string = '01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16';
$array  = array_map('str_getcsv', explode('|', $string));

Comments

0
$arr1 = explode("|",$yourString);
$arr2 = array();
for ($i=0;$i<count($arr1);$i++)
    $arr2[] = explode(",",$arr1[i]);

Comments

0
$str = "01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16 ";
$array = explode('|', $str);
$final_array = array();
foreach($array as $val)
{
    array_push($final_array, explode(',', $val));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.