PHP - Multidimensional Array - php

I am basically trying to fetch results from a SQL database and load that into a multidimensional array so i can use them later on in the page.
while($row = mysqli_fetch_array($result))
{
$send = array
(
array($row['Name'],$row['Email'],$row['Mobile'])
);
$count = $count + 1;
}
That is what i am using to get the results which if i print within the while loop it will echo all the results. However when putting it into the array it loads each result into the array as the first result. My initial plan was to use a counting variable to set where in the array the result was set to with this adding by one each time. I am not certain how to specify where to add the result i thought something along the lines of
$send = array[$count]
(
array.....
so i could then refer to the results as 0 to count length but i am not sure how to make this work. Or ,which i presume, if there is a much easier and better way of going about it. I am also not sure if this is necessary as surely the results seem to be in an array when gathered from the SQL database but i am unsure if this array is populated with each while loop or stored and can be accessed at any point
If any one can give me an example of something similar or point me at some documentation much appreciated

Try this:
$count = 0;
while ($row = mysqli_fetch_array($result)) {
$send[$count] = array($row['Name'], $row['Email'], $row['Mobile']);
$count++;
}
I have a better way for you. You could also use the id for your index, if you have one:
while ($row = mysqli_fetch_array($result)) {
$send[$row['id']] = array(
"Name" => $row['Name'],
"Email" => $row['Email'],
"Mobile" => $row['Mobile']
);
}

You can use:
$count = 0;
while($row = mysqli_fetch_array($result))
{
$send[$count] = $row;
$count ++;
}
Also you might want to use the table id as an array index, so you can access the records by ID later. In that case you can do:
while($row = mysqli_fetch_array($result))
{
$send[$row['id']] = $row;
}

You're declaring your array inside your loop. So it will reset it every time.
$send = array();
while($row = mysqli_fetch_array($result))
{
$send[] = array($row['Name'],$row['Email'],$row['Mobile']);
}

Related

Create array in PHP from mysql

I think that I may be over trying things with little sleep but I am having problems creating arrays from mysql queries. I have a query like so:
$result = mysqli_query($con,"SELECT * FROM vehicles ORDER BY id");
while($row = mysqli_fetch_array($result)) {
$description = $row['description'];
$description = strtoupper($description);
$id = $row['id'];
}
I want it to create an array like so:
$v[1] = "Myarray1";
I have tried this but it does not work:
$v[ $row['id']] = $row;
Do I have to query like this:
while( $row = mysql_fetch_assoc( $result)){}
and if I do, how I do create the array as I need it?
Many thanks in advance
At no point are you creating an array here. In your loop you are simply modifying some variables that in the context you posted I cannot reason on.
If all you need, no data filtering whatsoever this will do:
$list = Array();
while( $row = mysqli_fetch_array($result) ) {
$list[] = $row;
}
[] basically 'appends' in PHP, it is an ugly mechanism but it works.
If you want to access rows per primary key ( id in your case I think ) then simply replace [] with [$row["id"]]
I'm not exactly sure of the end result you're looking for. But if you want to access the results as $row['column'], where 'column' is a column name in your MySQL database, then you need to use mysql_fetch_assoc. I think this example will help:
while (($row = mysqli_fetch_assoc($result))) {
$v[$row['id']] = $row;
}
$v[1]['description'] is the data in the column description for the record with an id=1

Set Indexes on array of returned MySQL Values

Im trying to set the indexes of a 2d PHP array from numeric indexing to keys. What I have so far is :
$result = mysql_query("SELECT * FROM settings");
if(mysql_num_rows($result) > 0 ){
while($row = mysql_fetch_assoc($result)){
$dataArray[] = $row ;
}
}
$value_to_display = $dataArray[0]['value'];
However, what I'd like to be able to use is something like this :
$value_to_display = $dataArray['some_index_value']['value'];
Anyone know how I can achieve this ? Ive tried replacing making a keys array and then using combine, but I can only do this manually. Any help is appreciated!
How about
while ($row = mysql_fetch_assoc($result)) {
$dataArray[$row['somefield']] = $row;
}
Assuming that somefield is unique, you'll get an array keyed by that field's values. If you need to key names to come from somewhere else, e.g.
$keynames = array('foo', 'bar', 'baz', ....);
$idx = 0;
while($row = mysql_fetch_assoc($result)) {
$dataArray[$keynames[$idx]] = $row;
$idx++;
}
just make sure you have enough keynames to handle all the records you get back from the query.

PHP: Get element of an array

I have an element stored in the following way:
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["data"]. "</td></tr>";
$data1= floatval($row["data"]);
...
It is a value extracted from a MySQL database, and thus it is stored this way. If I want to get the value of the iteration let's say "i", it is easy, as I do not have to do anything else but how can I obtain the following value in order to perform a substraction? That's to say, data2 - data1? I thought about something similar to $row["data"][i], but I'm not sure it'll work. Thanks!
As you can see in the manual of fetch_assoc this function fetches only one row at a time and that's why we're using a loop.
The same goes for fetch_array and fetch_row.
mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row
as an associative array
The only solution that I can think of is to loop that array and to store that data in another array according to your requirements, for instance:
$customArr = array();
$i = 0; //counter.
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["data"]. "</td></tr>";
$data1= floatval($row["data"]);
$customArr[$i] = array('id' => $row['id'], 'date' => $date1);
}
Later on, if you want to compare values in the array you should use while and index-based scenarios like $customArr[$i-1], $customArr[$i].
Just make sure that you check the offset.
$i = 0;
while($i < count($customArr)){
}

While loop showing only one result

I want to show string outside while loop, but it only shows one result.
while($row = $result->fetch_assoc()) {
$myarr = array();
}
echo $myarr;
This shows only one result but I need all the results outside the while loop.
Could you please help me how is this possible?
I am not sure if you want the whole row returned from the query or just a single field.
If its the whole row then try
$myarr = array(); // initialize
while($row = $result->fetch_assoc()) {
$myarr[] = $row;
}
print_r($myarr);
This will give you an array containing n row arrays.
Problem :
You are just assigning the result one after again
$myarr = array();
Here, It means you're assigning the array() again and again, which replaces the old value
Solution / What You should do
1. You can assign it to an Array (Good Approach)
while($row = $result->fetch_assoc()) {
$myarr[] = $row['yourdbitem']; // or $row if you want whole row
}
print_r($myarr);
2. You can concat in each iteration (Bad Approach)
$somevariable = '';
while($row = $result->fetch_assoc()) {
$somevariable .= $row['yourdbitem']; // or $row if you want whole row
}
echo $somevariable
Note :
I have given good and bad approach to updating what you should do and what you should not do :)

while loop into in array

What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}

Categories