...

View Full Version : Resolved Explode String Twice into an Associative Array



RonnyNishimoto
08-15-2012, 05:23 AM
I have a string that is formatted like this:



Tom&Riddle?Jerry&Springer?Kobe&Bryant... and so on.


What I'm trying to do is get it to look like this:



$array = array(Tom => Riddle, Jerry => Springer, Kobe => Bryant);


I figured out how to explode the string from "?" with:



$divide = explode("?", "Tom&Riddle?Jerry&Springer?Kobe&Bryant");


but then I can't use explode again, since it only works with strings. I also found a foreach loop from google but I ended up getting separate arrays like:



foreach($array as $key=>$value) { $divide[$key] = strpos($value, "&") ? explode( "&", $value ) : $value;


Outputs:


array("Tom","Riddle");
array("Jerry","Springer");
array("Kobe","Braynt");


Maybe there is some way to turn ^ into an associative array?

I am completely lost? :confused:

Len Whistler
08-15-2012, 05:47 AM
But then I can't use explode again, since it only works with strings.





<?php
$results = explode("?", "Tom&Riddle?Jerry&Springer?Kobe&Bryant");

foreach ($results as $value){
$results = explode("&", $value);

foreach ($results as $value){
echo "$value<br>";
}
}


?>


Output

Tom
Riddle
Jerry
Springer
Kobe
Bryant


-------

kbluhm
08-15-2012, 09:15 PM
Here's a method to get the values into an array, as you'd originally asked... as opposed to simply printing them to the client:


$str = 'Tom&Riddle?Jerry&Springer?Kobe&Bryant';

$arr = array();

foreach ( explode( '?', $str ) as $val )
{
// we're assuming each piece will always have a `&` separating non-empty values
$val = explode( '&', $val );
$arr[ $val[0] ] = $val[1];
}

// What'd we get?
print_r( $arr );

RonnyNishimoto
08-15-2012, 10:25 PM
Kbluhm, perfect answer, I'm terrible with foreach statements so I tried using workarounds, but your answer works just how I wanted! Thanked and reputation added!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum