The title isn't 开发者_开发知识库very descriptive and I apologize, but I couldn't think of a better way to explain it. I have up to 10 serialized arrays in a database. I pull them down and unserialize them into a new array as such:
$specimen0 = unserialize($row['specimen0']);
$specimen1 = unserialize($row['specimen1']);
This is then formatted into an ordered list showing the specimens. Since there is a ton of data for each specimen I don't want to code it over and over again 10 times. My while loop looks as such:
while($i <= $num) {
if(isset($specimen{$i})) {
echo 'Yep';
}
$i++
}
That is the generalized version. For some reason the i variable isn't appending itself to the specimen variable to create the one size fits all variable I want. This is probably something simple that I'm over looking or php won't handle it the way I need. Any help would be greatly appreciated.
while($i <= $num) {
$target='specimen'.$i;
if(isset($$target)) {
echo 'Yep';
}
$i++
}
look at variable variables
Fatherstorm described how to correct you code very well. what makes me wonder is this: why don't you use an array like this:
$specimen = array();
$specimen[0] = unserialize($row['specimen0']);
$specimen[1] = unserialize($row['specimen1']);
// maybe you could also use an foreach($specimen as $key=>$array) here,
// don't know what you're trying to do...
while($i <= $num) {
if(isset($specimen[$i])) {
echo 'Yep';
}
$i++
}
otherwise you would have to use variable variables like the others mentioned - and this will end up in unreadable (and unmaintainable) code. if you want to use something like an array, take an array for the job.
while($i <= $num) {
$var='specimen'.$i;
if(isset(${$var})) {
echo 'Yep';
}
$i++
}
what you tried to do:
$str='abcdef';
echo $str{4}; //echo e;
$i=3;
echo $str{$i};//echo d
精彩评论