Forums

create dropdown from array

cornelio 29 Dec, 2015
Hi,

i have this form for create dropdown from array
<?php 
/* Array Contents */

$array_p = array('product1','product2','product3','product4','product5');
echo '<select name="product[]" multiple>';

for ($i = 0; $i < count($array_p); $i++)
{
echo '<option value="' . ($i + 1) . '">' . $array_p[$i] . '</option>';
} 
echo'</select>';
?>


Now I would like to begin with an array like this and enter into the Option Value the price as VALUE using this array:

$array_p = array([{"price1":"10","name":"product1"},
{"price2":"25","name":"product2"},
{"price3":"25","name":"product3"},
{"price4":"25","name":"product4"},
{"price5":"15","name":"product5"}]);


I tried, but I have not gotten results.

thenks a lot
Cornelio
GreyHead 29 Dec, 2015
Hi Cornelio,

The data in your last example isn't really an array - it's a string that contains a JSON encoded array, try using json_decode('your_string', true); to convert it back to an array.

Bob
cornelio 30 Dec, 2015
Hi Bob,
thank you very much for your attention, as always.
sorry for my bad english, probably the post has been set wrong.
I try to synthesize

a) I'm a dropdown multiple-select like this;
<?php
$content = '{"values":[{"price":10.5,"product":"book1688px"},{"price":10,"product":"book2356px"},{"price":70,"product":"book3421px"}]}';
    
	$jsonArray = json_decode($content, false);?> 
	<div>
	<select name="product[]" multiple>
	<?php 
     foreach($jsonArray->values as $jsonValue) { 
	 ?>
<option value="<?php echo $jsonValue->price; ?>">€ <?php echo $jsonValue->price; ?>--><?php echo $jsonValue->product; ?></option>
<?php } 
?>
</select>


b) in the setup in custom code I included: echo json_encode ($ form-> data ['product']);


c) they select the e.g. the first 3 products;

d) on submit to get the array corresponding to the value of the select with this result: ["1", "2", "3"];

question:

in practice how to format an array like ours ($ content) and save it to db for use in a dropdown like this?

Regards
Cornelio
GreyHead 31 Dec, 2015
Hi Cornelio,

I don't really understand what your question is :-(

Is it useful to set the price as the value of the drop-down options? Is that enough to identify the product uniquely?

Bob
This topic is locked and no more replies can be posted.