在if语句中使用由ms_sql查询生成的数组的第一个值
Ok, so basically I have a query that returns an array, and then it gets looped:
$result = mssql_query("SELECT * FROM Segments ORDER BY Squares");
if (!$result) {
echo 'query failed';
exit;
}
while ($row = mssql_fetch_array($result)) {
$txtsquares = $row["Squares"];
echo $txtsquares;
When echoed the variable $txtsquares is equal to an array value, for example lets say 1 2 3 4 5 6 7 8.
I need this array/loop. But I would like to grab the first value of this array and use it in an if statement, like so:
value="<?php echo $txtsquares; ?>"
<?php if ($txtsquares == 1) { ?> checked="checked" <?php }
else{ ?> checked="" <?php } ?>/>
However obviously this is wrong, because the value will never equal 1 because its an array. Can anyone point me in the correct direction? I am new at PHP so sorry if it is an easy question, I have Googled it but without much luck.
好的,基本上我有一个返回数组的查询,然后它被循环: p> \ n
$ result = mssql_query(“SELECT * FROM Segments ORDER BY Squares”);
if if(!$ result){
echo'query failed';
exit;
while($ row = mssql_fetch_array($ result)){
$ txtsquares = $ row [“Squares”];
echo $ txtsquares;
code> pre>
当回显变量$ txtsquares等于数组值时,例如假设1 2 3 4 5 6 7 8. p>
我需要这个数组/循环。 但是我想获取这个数组的第一个值并在if语句中使用它,如下所示: p>
value =“&lt;?php echo $ txtsquares;?&gt ;“
&lt;?php if($ txtsquares == 1){?&gt; checked =“checked”&lt;?php}
else {?&gt; checked =“”&lt;?php}?&gt; /&gt;
code> pre>
但显然这是错误的,因为该值永远不会等于1,因为它是一个数组。 谁能指出我正确的方向? 我是PHP新手,很抱歉,如果这是一个简单的问题,我用Google搜索但没有太多运气。 p>
div>
If you need to use the first element of $txtsquares
try this:
value="<?php echo $txtsquares; ?>"
<?php if ($txtsquares[0] == 1) { ?> checked="checked" <?php }
else{ ?> checked="" <?php } ?>/>
Assuming $txtsquares
is a string of numbers, and you know it's a string of numbers... you could do something like this:
$txtsquares = "1234";
$str_values = str_split($txtsquares);
// array('1', '2', '3', '4')
$int_values = array_map(function($i) { return (int)$i; }, $str_values);
// array(1, 2, 3, 4)
$first_value = $int_values[0];