badr aldeen
badr aldeen

Reputation: 470

convert a string to multi dimensional array in 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} };

Upvotes: 4

Views: 9261

Answers (5)

naffiq
naffiq

Reputation: 1050

You have almost done it right, except for the cycle part. Try this

$result = [];
$String = 'a,b,c|d,e,f|g,h,y|';

$firstDimension = explode('|', $String); // Divide by | symbol
foreach($firstDimension as $temp) {
    // Take each result of division and explode it by , symbol and save to result
    $result[] = explode(',', $temp);
}

print_r($result);

Upvotes: 2

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Try this-

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

$one = array_filter(explode("|", $String));

print_r($one); //Array ( [0] => a,b,c [1] => d,e,f [2] => g,h,y ) 

$result = array_map('v', $one);

function v($one) {
    return explode(',',$one);
}

print_r($result); // Array ( [0] => Array ( [0] => a [1] => b [2] => c ) [1] => Array ( [0] => d [1] => e [2] => f ) [2] => Array ( [0] => g [1] => h [2] => y ) )

Upvotes: 1

YyYo
YyYo

Reputation: 641

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.

Upvotes: 2

Sunil Pachlangia
Sunil Pachlangia

Reputation: 2071

Use this code

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

$one=explode("|",$String);

print_r(array_filter($one));

Output will be

Array
(
    [0] => a,b,c
    [1] => d,e,f
    [2] => g,h,y
)

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31749

Try with -

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

Upvotes: 4

Related Questions