0

i wanna Split this string retrieved from database with the help of PHP.

String Rahul:12345644,Jatin:23452223,Raman:33343212

How could i show this in below result format.

  Array
    (
        [0] => Rahul 
            (
                [0] => 12345644
            )

        [1] => Jatin
            (
                [0] => 23452223
            )

        [2] => Raman
            (
                [0] => 33343212
            )

    )   

I tried this with

$arrayData = explode(",", $data);

the result is

Array
        (
            [0] => Rahul :12345644
            [1] => Jatin :23452223               
            [2] => Raman :33343212
        )

and after

foreach($arrayData as $eachValue) {
 echo $eachValue;
}
3
  • 1
    You can't.... your required result isn't a valid array: an array element can't be both a string value and an array at the same time Commented Jan 7, 2013 at 11:51
  • k.. can i get another solution.. Commented Jan 7, 2013 at 11:52
  • Show what you actually want, and as long as it's valid we can try to give you a solution Commented Jan 7, 2013 at 11:53

2 Answers 2

2

Perhaps:

$resultArray = array();
$arrayData = explode(",", $data);
foreach($arrayData as $eachValue) {
    $resultArray[] = explode(':',$eachValue);
}

which is (at least) a valid array structure

Array ([0] => Array ([0] Rahul 
                     [1] => 12345644
                    )
       [1] => Array ([0] Jatin
                     [1] => 23452223
                    )
       [2] => Array ([0] Raman
                     [1] => 33343212
                    )
     )
Sign up to request clarification or add additional context in comments.

Comments

1

If you're willing to change the format so that you use equal signs and ampersands, you could use the PHP built-in function parse_str().

eg:

$input = "Rahul=12345644&Jatin=23452223&Raman=33343212";
parse_str($input, $output);
print_r($output);

gives:

Array
(
    [Rahul] => 12345644
    [Jatin] => 23452223
    [Raman] => 33343212
)

That's pretty close to what you're after.

If you want to keep your existing format but still use parse_str(), you could use str_replace() or strtr() or similar to swap the colons and commas just for the call to parse_str():

$input = "Rahul:12345644,Jatin:23452223,Raman:33343212";
parse_str(strtr($input,':,','=&'),$output);

Hope that helps.

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.