I’m trying to loop through mysql query results inside of a loop and add them to an array.
//initialize array
$people = array();
//build array of names & numbers
while ($row = mysql_fetch_assoc($result))
{
$to = $row['text'];
$fname = $row['fName'];
$people = array(
$to => $fname
);
}
Not sure what I’m doing wrong…
SamA74
December 13, 2016, 7:07pm
2
What I do is build a temporary array within the loop, then add that to the parent array at the end.
while($row = $sql->fetch()) {
$temp['to'] = $row['text'];
$temp['fname'] = $row['fName'];
// Etc...
$people[] = $temp;
$temp = NULL ; // reset the temp array at end of loop
}
Maybe
$people[] = array(
$to => $fname
);
Also look at moving on from the old-style MySQL library calls to access the database, either to mysqli or PDO.
1 Like
SamA74
December 13, 2016, 7:13pm
4
It really depends on the exact structure of data you want to end up with.
Simply taking one array ($row
) and putting it into another identical array called $people
is kind of pointless. So I presume there is some further processing of the data going on.
I’m going to use the array in a for loop. The format of the array should be:
$people = array(
"5558675309" => "Aaron",
"6666666666" => "Joe",
"4444444444" => "Jane"
);
foreach ($people as $number => $name) {
...
}
SamA74
December 13, 2016, 7:35pm
7
That should be simple enough.
{ $people[$row['number']] = $row['fname']; }
Sorry, but I’m still not sure…
Is this what you mean?
$result = mysql_query($query);
$people = array();
while ($row = mysql_fetch_assoc($result))={
$people[$row['number']] = $row['fname'];
}
SamA74
December 13, 2016, 8:22pm
9
aaron4osu:
Is this what you mean?
Yes. But no need to create the array before the while.
Going by your first post, number
shoud be text
. I just made up that column name.
Thanks that got it working!
Forget mysql_fetch_assoc().
Forget loops.
mysql_fetch_assoc(), along with all its sister functions has been removed from PHP a year ago. Not to mention there are other ways to get what you want right from the query, without any loops at all. Namely PDO.
$stmt = $pdo->query("SELECT number, fname FROM whatever")
$people = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
This. Is. All.
You can learn more about PDO from the tutorial I wrote
1 Like
system
Closed
March 17, 2017, 3:56pm
12
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.