1

I have this array returned by the db

Array ( [0] => Array ( [id] => 3 [test] => alphy,poxy,jade,auma ) ) 

Then i have used explode to separate the values

$options = explode(",", $test1['0']['test']);

the result is

 array(4) { [0]=> string(5) "alphy" [1]=> string(4) "poxy" [2]=> string(4) "jade" [3]=> string(4) "auma" }

I then count the number of the values

$count= substr_count($test1['0']['test'], ",")+1;

I then now try to create textareas dynamically based on the count and values e.g text area 1 - alphy, textarea2 - poxy ...

  for($i=0; $i<=$count;$i++){?>
            <textarea ><?php echo $options[$i]['test']?> </textarea>
    <?php }?>

The above is not doing, instead each textarea has just the first letter such as a, p, j, a instead of alphy , poxy, juma, auma.

What am i missing?

4

1 回答 1

2

只需迭代 $options 数组即可打印出您的 textareas - 无需获取计数。

$test1 = array(array('id' => 3, 'test' => 'alphy,poxy,jade,auma')); 
$options = explode(",", $test1['0']['test']);
foreach ($options as $i => $option) {
    echo '<textarea name="textarea_' . $i . '">' . $option . '</textarea>';
}

当然,如果你真的想使用计数,你可以这样做:

$test1 = array(array('id' => 3, 'test' => 'alphy,poxy,jade,auma')); 
$options = explode(",", $test1['0']['test']);
$count = count($options);
for ($i = 0; $i < $count; $i++) {
    echo '<textarea name="textarea_' . $i . '">' . $options[$i] . '</textarea>';
}

编辑:鉴于对您问题的编辑,您似乎正在尝试访问每个选项的索引(“测试”)。但是一旦它们被分割成一个数组,它们就变成了简单的字符串,所以不需要像数组一样尝试访问它们。

你得到第一个字母的原因是因为$x = 'alpha'; $x['test']计算结果为$x[0],它访问字符串中的第一个字符,即a.

于 2013-06-30T11:28:04.283 回答