Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a string to multi dimensional array in php

Tags:

arrays

types

php

I'm having trouble converting a string to a multi-dimensional array in php. This is my string:

$String = a,b,c|d,e,f|g,h,y|

This is what I'm trying:

$one=explode("|",$String);
foreach ($one as $item)
{
    $one=explode(",",$one);
}

I'd like to create this array:

$array={ {a,b,c}, {d,e,f}, {g,h,y} };
like image 360
badr aldeen Avatar asked Jan 08 '23 13:01

badr aldeen


2 Answers

Try with -

$one=explode("|",$String);
$array = array();
foreach ($one as $item){
    $array[] = explode(",",$item);
}
like image 70
Sougata Bose Avatar answered Jan 15 '23 12:01

Sougata Bose


Try this code:

$string = 'a,b,c|d,e,f|g,h,y|';
$arr = array_map(function($iter){ return explode(',',$iter);},explode('|',$string));

Hope it help a bit.

like image 22
YyYo Avatar answered Jan 15 '23 13:01

YyYo