4

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} };

5 Answers 5

4

Try with -

$one=explode("|",$String);
$array = array();
foreach ($one as $item){
    $array[] = explode(",",$item);
}
Sign up to request clarification or add additional context in comments.

1 Comment

i'm sorry i don't know why it's didn't work with me in the first time i did it again and it's work maybe i made a mistake in that time thank you so much
2

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.

Comments

2

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);

Comments

1

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
)

3 Comments

this one is just print array and one dim array not two also you didn't split " , "
Please check it again please if it is producing required data.
thanks for your help but what i need is not what you wrote above you can check my question again the output is different
1

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 ) )

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.