PDA

View Full Version : Array String into Associative Array


cupOfBlue
08-18-2006, 05:05 PM
On one server I have a mysql query pulling data out of a database, and then printing the results. These results are then pulled from another server

$result = implode(file('http://www.fakesite.com/query.php');

the page result is like this - Array ( [index] => 1 [title] => test [author] => [authorEmail] => [filename] => blah [startDate] => 0000-00-00 [expireDate] => 0000-00-00 [priority] => 0 [interesting] => 0 [ap] => 0 [relatedStories] => [tags] => [blurb] => [article] => [sections] => [deprecated] => [hits] => 0 [pageCreated] => 0 [extraAttributes] => [forumPostStatus] => 0 [tagLine] => ) (note that this result would not always contain the same fields)

but it's a string, rather than the array it was on the other page. Is there a way to turn this into the same array it was before, without a long process of replacing items in the string?

Fumigator
08-18-2006, 05:31 PM
Your file() function creates an array, but that implode() function is gluing the array pieces together and creating a string, so if you want an array just keep implode() out of it.

cupOfBlue
08-18-2006, 05:42 PM
Removing the implode would keep it as an array, just not the correct array. The keys would be the line numbers, rather than the keys generated by the mysql query. What I'm looking for is a function that would translate the string to that original array, if it exists

I'm guessing there is no current function for that, atleast not one that is a part of php, just thought I'd ask.

Fumigator
08-18-2006, 06:03 PM
Certainly there's many ways to reconstruct an associative array.

One option that wouldn't be too painful for what you have going on is to change the way your query.php script prints the array. For example, make key and value delimited by a string separator you wouldn't see in your data:

foreach ($queryResult as $qKey = $qVal) {
print $qKey . ";:;:;" . $qVal . "\n";
}


Now in the script you want to reconstruct this array, use file() to create an array, then use explode to grab the key and value and reconstruct the original array:

$rawArray = file("....query.php");
foreach($rawArray as $rVal) {
list($qKey, $qVal) = explode (";:;:;", $rVal);
$qArray[$qKey] = $qVal;
}


This is just one of several viable options.

cupOfBlue
08-18-2006, 06:14 PM
Awesome, that worked, thank you very much