PHP multidimensional array from database results - php

I'm a bit new to multidimensional arrays, and would like to see if I'm doing it right. preferably, I'd like to name the arrays within the main array for ease of use.
$unique_array = array(
username=>array(),
user_id=>array(),
weeknumber=>array()
);
and then I have a while loop which checks some database results:
while($row = mysql_fetch_array($query)) //yes, I know mysql is deprecated
{
$unique_array[] = username=>$row['username'], user_id=>$row['user_id'], week number=>['weeknumber'];
}
I'm not sure if I am placing the values in the array from within the while loop correctly, or if it needs to be done some other way. I couldn't find any resources I could easily understand on SO or elsewhere to deal with query results within a named array within a multidimensional array.
EDIT FOLLOW UP QUESTION: I also need to check the array for duplicate values, because there will be multiple values that are exactly the same, but I only want one of them.
Any help is appreciated!
EDIT SOLUTION:
By modifying the answer I was able to create code to fit my needs.
Array initialization:
$unique_array = array(
'username'=>array(),
'user_id'=>array(),
'weeknumber'=>array()
);
Building the array from within a while loop:
while($row = mysql_fetch_array($query))
{
$unique_array[] = array('username'=>$row['username'], 'user_id'=>$row['user_id'], 'weeknumber'=>$row['weeknumber']);
}
And finally, I need to make sure the array values are unique (there are duplicates entries as a result of database and query limitations), after the while loop I have:
print_r(multi_unique($unique_array));

Is the top level an associative array or a numeric array?
If it is an associative array, it should have structure like this:
$unique_array = array(
'username'=>array('John','Mike',...),
'user_id'=>array(1,2,3,...),
'week_number'=>array(1,2,3,...)
);
Or if it is a numeric array, it should have structure like this:
$unique_array = array(
array('username'=>'John', 'user_id'=>1, 'week_number'=>1),
array('username'=>'Mike', 'user_id'=>2, 'week_number'=>2),
array('username'=>'Sam', 'user_id'=>3, 'week_number'=>3),
...
)
for the first type use the code below:
while ($row = mysql_fetch_assoc($query)) {
$unique_array['username'][] = $row['username'],
$unique_array['user_id'][] = $row['user_id'],
$unique_array['week_number'][] = $row['week_number'],
}
for the second type, it is something like your code. But there are some syntax problems:
while($row = mysql_fetch_array($query)) //yes, I know mysql is deprecated
{
$unique_array[] = array('username'=>$row['username'], 'user_id'=>$row['user_id'], 'week_number'=>$row['weeknumber']);
}

Related

How to add resultset rows to a result array as indexed subarrays?

I have a mysqli resultset with two columns of data and several rows. I want to store each row of the resultset as an indexed subarray in my result array (specifically in $rows['data']).
This is my current code:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while ($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
This results in an array that looks like this:
{"name":"Total_watts","data":[1519334969,259,1519335149,246,1519335329,589,1519335509,589,1519335689,341,1519335869,341,1519336050,523,1519336230,662,1519336410,662,1519336590,469]}
But I need the result to be an array that looks like this:
{"name":"Total_watts","data":[1519334969,259],[1519335149,246],[1519335329,589],[1519335509,589],[1519335689,341],[1519335869,341],[1519336050,523],[1519336230,662],[1519336410,662],[1519336590,469]}
Can someone suggest a change in the PHP while loop to produce this output?
You just need to adjust your syntax to place the elements in the same subarray.
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
p.s. Additionally, you could use mysqli_fetch_assoc() since you are only accessing the associative keys. Or even better, use mysqli_fetch_row() and assign the row to your result array.
All baked, it could look like this:
if(!$result=mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings")){
// handle the query error
}else{
$rows=['name'=>'Total_watts'];
while($row=mysqli_fetch_row($result)){
$rows['data'][]=$row; // this will store subarrays like: [1519334969,259]
}
}

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'];
}

making three dimensional array that has an unknown amount of arrays inside

I'm trying to store data from a table, and I do not know how many lines will be in said table. My idea was to make a main array called data, a sub array for each line with just numeric labels (1,2,3,etc) and then inside each of those would be the actual data from each line, so it would be like this:
data
->1
->item1
->item2
->item3
->2
->item1
->item2
->item3
->3
->item1
->item2
->item3
ETC. I know how to work with multidimensional arrays and I know there are easy ways to accomplish this in java, but I can't for the life of me figure out how to do it in php.
To keep on adding to an array simply use the following code:
$myArray[] = 'another value';
Notice the [] this tells php to add another value to the array (without removing previous elements)
See here for a quick tutorial on mutidimensional arrays:
http://webcheatsheet.com/PHP/multidimensional_arrays.php
And this:
http://www.developerdrive.com/2012/01/php-arrays-array-functions-and-multidimensional-arrays/
Try,
foreach($rows as $v) {
$data[] = array($v['item1'], $v['item2'], $v['item3']);
}
To map mySQL data to a multidimensional array:
$query = mysql_query("SELECT * FROM table WHERE uid = '1' ORDER BY id DESC");
$results = array();
$i = 0;
while($line = mysqli_fetch_array($query, MYSQL_ASSOC)){
$results[$i] = $line;
$i++;
}

PHP: Unexpected behavior: foreach... {$array['country'][] = $value['country']}

Why does the operator
$array['country'][] return what logically would be $array[]['country']?
What I am saying is this. If you want to extract from a MySQL array, the value of ['country'] for every row, [1],[2]...[n], you have to use
$array['country'][]
despite fact that they are ordered as
$array['row#']['country']
Is this because PHP is reading something backwards, or because I am just lacking some fundamental array information?
FULL-ish code here
$result = array();
foreach($data as $value){
$array['country'][] = $value['country'];
$array['report'][] = $value['report'];
}
$data = $array;
Let me know if I am just dumb... I can't really grasp why this is working this way.
get an id from the db
SELECT id,country,report from yourdb
while ($row = mysql_fetch_array($result)) {
$array['country'][$row['id']] = $row['country'];
$array['report'][$row['id']] = $row['report'];
}
create an id
SELECT country,report from yourdb
$i=0
while ($row = mysql_fetch_array($result)) {
$array['country'][$i] = $row['country'];
$array['report'][$i] = $row['report'];
$i++
}
Why does the operator
$array['country'][]
return what
logically would be
$array[]['country']?
It is because you are constructing the array in that way:
If you use $array['country'][] = $value['country'];, you are adding a new value to the sub-array which is part of the containing array under the country key. So it will be mapped to $array['country'][], you cannot expect otherwise.
If you want it to map to array[]['country'], then (using part of code from
#Lawrence's answer), you'd have to add the new values using explicit numerical indexes as the key:
SELECT country,report from yourdb
$i=0;
while ($row = mysql_fetch_array($result)) {
$array[$i]['country'][] = $row['country'];
$array[$i]['report'][] = $row['report'];
$i++;
}
Assuming that $data has been built by you using a loop like what you pasted in the comments (while($row=mysql_fetch_assoc($result)){$data[]=$row;}) then my answer would be because that's exactly what you asked PHP to do.
The notion $data[] = some-value-here means take that value and add it with to the end of $data array with an auto-generated key I just don't care. That is, PHP will basically see what the last item's key is, add 1 and use that as the key for the item you are adding to the array.
So what you are doing with that loop is building an array whose keys are numbers starting from 0 and incrementing (+1 each cycle, this is the [] effect) and using these keys for the rows you are getting off the database result set.
If you want to access $data in the way you described, then you have to change the way you are building it. See Lawrence Cherone's answer for that.

Two dimensional associative array in PHP

In my code I'm getting data (three columns) from a sql db and I want to store the rows in an associative PHP array. The array must be multi-dimensional because I want to use the row id from the database as a key so that i can fetch values like this:
$products["f84jjg"]["name"]
$products["245"]["code"]
I've tried using the following code but it doesn't work:
while ($row = mysql_fetch_row($sqlresult))
{
$products = array($row[0] => array(
name => $row[1],
code => $row[2]
)
);
}
Also, how should I reference the key if it is taken from a variable? What I want to do is:
$productName = $products[$thisProd]["name"];
Will this work?
This should do it, assuming row[0]'s contents is a unique identifier (else you could override a row):
while($row = mysql_fetch_row($sqlresult)) {
$products[$row[0]] = array(
'name' => $row[1],
'code' => $row[2]
);
}
You need to put quotes around the array keys, and you were creating an array of array of arrays.
Also note you could use mysql_fetch_assoc instead of mysql_fetch_row, which would give you the array keys as the column names, which would make this much easier/cleaner:
while($row = mysql_fetch_assoc($sqlresult)) {
$products[$row['myidcolumn']] = $row;
}
After you do this, the code you described would work.

Categories