Jump to content

Output dynamic array values in json array.


fishbaitfood

Recommended Posts

Hello all,

 

I have yet again trouble finding a logical solution to my problem.

I'm fetching an array which can hold 1 or more values.

The problem is, I want these values to ouput in my json_encode function, but this also needs to happen dynamically depending on the amount of values.

 

I can't explain it further, so here's the code so far:

 

$files = mysql_fetch_array($get_files);

$a = count($files);

$i = 1;
while ($files) {
$variablename = 'fileName' . $i;
$$variablename = $files['fileName'];
$i++;
}

$output =  array( OTHER VALUES , 'fileName1' => $fileName1, 'fileName2' => $fileName2, 'fileName3' => $fileName3, ............);		// How do I add the fileNames dynamically depending on how many there are?

 

 

This got me thinking, I also need to dynamically GET the values with jQuery. How would I do that, when the above eventually works?

 

Thank you.

 

Thanks for your fast answer requinix!

 

How would I dynamically fetch those values with jQuery?

Maybe I could count the array in jQuery, then subtract the amount of other (standard) values, to get the amount of dynamic values?

Or is this much more easier to solve?

Because I need to be able to put those values where I want them on my webpage.

 

 

EDIT: with the above code, I get a syntax error, unexpected T_INC, expecting '}' on the line $output["fileName{$i++}"] = $files["fileName"];

Guess you can't post-increment. Moot point anyways.

 

Since apparently you don't need the "fileNameX" labels, just use an array:

$output[] = $files["fileName"];

json_encode() will spit out something like

["file1", "file2", "file3"]

which becomes a simple JavaScript array

var filenames = ["file1", "file2", "file3"];
alert(filenames[0]); // file1

Hmm, that would work, yes.

 

My output would be something like this:

 

output = array('customer' => $customer, 'address' => $address, '0' => file1, '1' => file2, '2' => file3, ...);

 

My goal is, with jQuery, to loop through the FILES ONLY, and make them radio button options.

 

Is this possible with the above output?

 

Appreciate your help, many thanks!

Thanks, requinix, that did the trick! :)

 

BUT, I can only receive ONE file, even when there are two, three, ...

 

I did some debugging, and when I execute the query in MySQL itself, I'm able to receive multiple filenames, as expected to work.

But when using the same query with PHP and using print_r, there's only ONE (the first) file in the array.

 

$select_files = "SELECT file FROM files WHERE customer = '$customer';";

 

How's this possible?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.