Page 1 of 1

[SOLVED] Correct MySQL column to array converting?

Posted: Sun Jun 27, 2004 11:19 am
by tomfra
How can I correctly convert data from one MySQL column to an array?

E.g. the string is:

Code: Select all

$string = $row['1'].",";
$array = explode (',', $string);
echo "$string";  
print_r ($array);
echo "$string"; returns correct results - i.e. something,something_else,something_else1 ...

Now I would like to convert the string it created to an array named $array. But when I explode $string (using comma as the separator because it was present in the original string) it doesn't convert it properly.

Instead of creating standard array where "something" is Array 0, "something_else" is Array 1 and "something_else1" is Array 2, it creates Array where "something" is Array 0, "something_else" is Array 1 *BUT* "something_else1" is again Array 0 despite it should be Array 2 and it goes on this way for the whole string.

It's driving me crazy! I have no idea where the problem is.

Thanks for any help.

Tomas

Posted: Sun Jun 27, 2004 1:31 pm
by scorphus
It seems that you are re-defining the $array variable on each loop. Post the entire code please and let us have a better idea of what is going on.

-- Scorphus.

Re: Correct MySQL column to array converting?

Posted: Sun Jun 27, 2004 1:54 pm
by McGruff
tomfra wrote:How can I correctly convert data from one MySQL column to an array?
It sounds like your db structure isn't properly normalised.

http://www.oreilly.com/catalog/javadtab ... r/ch02.pdf

Posted: Sun Jun 27, 2004 3:50 pm
by tomfra
McGruff,

I don't think it has much to do with the db structure because I am working with a string that has already been created from one of the db columns.

This string has values separated by commas so I use "explode" to convert this string to array. There may be a simpler solution but I feel more comfortable doing it this way.

I get something like this when I use echo $string:

Code: Select all

file1.ext,file2.ext,file3.ext,file4.ext,
Then after I explode this string I get this output after print_r ($string) I get this:

Code: Select all

Array
(
    [0] => file1.ext
    [1] => 
)
file2.ext,Array
(
    [0] => file2.ext
    [1] => 
)
file3.ext,Array
(
    [0] => file3.ext
    [1] => 
)
file4.ext,Array
(
    [0] => file4.ext
    [1] => 
)
I understand that Array 1 is there because of the extra comma but that's probably not the culprit. I think the problem is with a wrong while cycle - it grabs the right data into $string but then creates wrong array. Right now the code is very much in "testing mode" so posting it here would not help much.

Tomas

Posted: Sun Jun 27, 2004 4:39 pm
by tomfra
I found the right solution at http://www.phpbuilder.com/board/showthr ... d=10526788 .

Thanks everyone for your help!

Tomas