'Create simple numeric PHP array from MySQL result [duplicate]
If I create a manual array in PHP:
$numbers = array(3,5,7,8,10,12);
Then, inside a loop where $j is incrementing, I can use:
if (in_array($j, $numbers)) { //THIS } else { //THAT }
for some logic to do 'this or that' on the third, fifth, seventh, eighth, tenth and twelfth iteration of a loop.
I'd like the content of $numbers to come from a MySQL query result.
However, if I grab an array using the below code, the array is not built the same and I cannot reference it from in_array ($conn is obviously the connection details not provided here):
$numbers_from_query_sql= "SELECT (round*1) as round FROM event";
$numbers_from_query = mysqli_query($conn, $numbers_from_query_sql);
$numbers_ms_array= array();
while ($row = mysqli_fetch_assoc($numbers_from_query)) {
$numbers_ms_array[] = $row;
}
The var_dump($numbers_ms_array) of the above produces:
array(6) { [0]=> array(1) { ["round"]=> string(1) "3" } [1]=> array(1) { ["round"]=> string(1) "5" } [2]=> array(1) { ["round"]=> string(1) "7" } [3]=> array(1) { ["round"]=> string(1) "8" } [4]=> array(1) { ["round"]=> string(2) "10" } [5]=> array(1) { ["round"]=> string(2) "12" } }
If I then pass $numbers_ms_array to the in_array code, it does not work .
Note that in the database, the 'round' column is varchar(3).
How can I get a simple array (like my first manual example) from the result of my MySQL query (with all of the results as integers, if that's also necessary)?
Solution 1:[1]
You are assigning the whole $row to your numbers array which is giving you the entire row as an array in your values.
It sounds like you want only the value so you should assign just the column you want instead:
$numbers_ms_array[] = $row['round'];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cOle2 |
