Naresh
Naresh

Reputation: 2781

split normalized string in php and put in array?

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

Upvotes: 0

Views: 103

Answers (2)

SDC
SDC

Reputation: 14222

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.

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212412

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

Upvotes: 2

Related Questions