问题
I'm selecting a single column from my mysql database:
$savedSQL = 'SELECT can_id FROM savedsearches WHERE user_id = "'.mysql_real_escape_string($user_id).'" AND insertTime >= "'.$lastSigTime.'"';
$savedQuery = mysql_query($savedSQL);
And I'd like to return the values as a single dimension, enumerated array such that array[0] = row1, array[1] = row2, etc.
When I put it into an array like this:
while($savedResult = mysql_fetch_array($savedQuery))
{ $savedArray[] = $savedResult; }
It returns it as a multi-dimension array so that array[0][0] = row1, array[1][0] = row2, etc.
I was thinking of adding something like this:
while($i=0;$i<count($savedArray);$i++)
{
$newSavedArray[$i] = $savedArray[$i][0]
}
But is there an easier, more efficient way to accomplish this?
回答1:
You're very close. You just need to access $savedResult[0]
to retrieve your column, and append it onto $savedArray
while($savedResult = mysql_fetch_array($savedQuery)) {
$savedArray[] = $savedResult[0];
}
回答2:
while($savedResult = mysql_fetch_array($savedQuery)) {
$savedArray[] = $savedResult['can_id'];
}
回答3:
try
$savedArray[] = $savedResult['can_id'];
instead of
$savedArray[] = $savedResult;
回答4:
Here's a method with mysqli and no loop. It takes all your code down to only two lines.
$r = mysqli_query($c,'SELECT can_id FROM savedsearches WHERE user_id = "'.mysql_real_escape_string($user_id).'" AND insertTime >= "'.$lastSigTime.'"');
$savedArray = array_column(mysqli_fetch_all($r,MYSQLI_ASSOC),"can_id");
回答5:
When you initially get the results of mysql you can merge the contents of both while loops into one:
while($result = mysql_fetch_array($savedQuery)) {
$savedArray[] = $result[0]; // or $result['can_id']
}
来源:https://stackoverflow.com/questions/8204240/mysql-select-single-column-as-single-dimension-array-in-php