php string extraction problem
I have a st开发者_运维知识库ring containing values i.e.
'Acton $ 80 Ajax $ 80 Aldershot $ 80 Alliston $ 115 Alton $ 80 Aldershot $ 84 Alexandria $ 674'
I want to make:
<option value='80'> Acton </option>
<option value='80'> Ajax </option>
...and so on. How should I do this, using PHP?
$str = 'Acton $ 80 Ajax $ 80 Aldershot $ 80 Alliston $ 115 Alton $ 80 Aldershot $ 84 Alexandria $ 674';
$arr = explode(" ", $str);
for($i = 0; $i < count($arr)/3; $i+=3)
echo "<option value='".$arr[$i]."'>".$arr[$i+2]."</option>\n";
Try explode function. However, this code doesn't handle error input.
Working code:-
<?php
$str = 'Acton $ 80 Ajax $ 80 Aldershot $ 80 Alliston $ 115 Alton $ 80 Aldershot $ 84 Alexandria $ 674';
$arr = explode(" ", $str);
?>
<select>
<?php
$i = 0;
foreach($arr as $key=>$value) {
if($i == $key) {
?>
<option value="<?php echo $arr[$i+2] ?>"><?php echo $arr[$i] ?></option>
<?php
$i = $key+3;
}
}
?>
</select>
Hope this helps.
$tmp = explode(' ', $string);
$result = '';
while (!empty($tmp)) {
$name = array_shift($tmp);
$dollarSign = array_shift($tmp);
$value = array_shift($tmp);
$result .= "<option value='$value'>$name</option>";
}
精彩评论