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!

asked Jan 9, 2012 at 8:52
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.

Jordan Running
107k18 gold badges193 silver badges189 bronze badges
answered Jan 9, 2012 at 8:55
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

answered Jan 9, 2012 at 9:15

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));
answered Jan 9, 2012 at 9:15

Comments

0
$arr1 = explode("|",$yourString);
$arr2 = array();
for ($i=0;$i<count($arr1);$i++)
 $arr2[] = explode(",",$arr1[i]);
answered Jan 9, 2012 at 8:58

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));
}
answered Jan 9, 2012 at 8:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.