...

View Full Version : explode a string into 2 arrays



Dubz
11-22-2011, 12:24 AM
I'm wondering how i can change a string to an array using a character between.
Something like this:


$string = "tree=papaer|plastic=bottle";

foreach(explode('|',$string) as $variabe){
//Splits it to "tree=paper" and "plastic=bottle" in $variable

//How do i change $variable to '$source => $outcome'?
}


So in the example it would split each part of the string separated with pipes into another string with a looping function (to do for each one). Then it processes that and splits it again with another special character (an equal sign in this case) and splits it into either an array or two separate strings.

Adee
11-22-2011, 12:40 AM
<?php


$string = "tree=papaer|plastic=bottle|metal=wire";



$piped = explode("|", $string);

foreach($piped as $equals)
{
$a[] = explode("=", $equals);
foreach($a as $b)
{
$data[$b[0]] = $b[1];
}
}



print_r($data);


?>



Array
(
[tree] => papaer
[plastic] => bottle
[metal] => wire
)

Dubz
11-22-2011, 12:51 AM
<?php


$string = "tree=papaer|plastic=bottle|metal=wire";



$piped = explode("|", $string);

foreach($piped as $equals)
{
$a[] = explode("=", $equals);
foreach($a as $b)
{
$data[$b[0]] = $b[1];
}
}



print_r($data);


?>



Array
(
[tree] => papaer
[plastic] => bottle
[metal] => wire
)


Yeah I just figured it out but I think I like your way better than mine so I might use it. Thanks!

kbluhm
11-22-2011, 02:04 AM
Eh, that solution is overly complex.

It is almost a query string, so simply convert it to a query string and parse it with parse_str (http://php.net/parse_str)():


$string = "tree=papaer|plastic=bottle|metal=wire";

$string = str_replace( '|', '&', $string );

parse_str( $string, $data );

print_r( $data );



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum