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++;
}
Related
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']);
}
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'];
}
I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);
I'm playing with a guestbook/chatroom idea and have a MySQL table setup with three columns:
1 - id - Primary Key auto increment
2 - name - String
3 - comment - string
I have very little experience with PHP but this is what I've put together for this operation:
$result = mysql_query("SELECT * FROM guestbook");
$i = 0;
while($row = mysql_fetch_array($result))
{
//add the row to the $chat array at specific index of $i
$chat[$i] = $row;
$i += 1;
}
$encode = json_encode($chat);
echo "$encode";
However, output from this looks pretty awful:
[{"0":"1","id":"1","1":"Justin ","name":"Justin ","2":"Comment 1","comment":"Comment 1"},
{"0":"2","id":"2","1":"Justin ","name":"Justin ","2":"Another comment","comment":"Another comment"},
{"0":"3","id":"3","1":"Justin ","name":"Justin ","2":"Look at this comment!","comment":"Look at this comment!"},
{"0":"4","id":"4","1":"Justin ","name":"Justin ","2":"Ok I'm done talking","comment":"Ok I'm done talking"}]
I was hoping to get three fields: id, name, and comment, but it looks like things doubled. Can anyone help?
Thanks!
To paraphrase Marc, Just replace this line:
while($row = mysql_fetch_array($result))
With this:
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
To get cleaner JSON. By default mysql_fetch_array() will return both an integer index and an associative index, you only want the associative index.
mysql_fetch_array returns a compound array: indexed AND keyed. To fetch just one or the other, use mysql_fetch_row() (indexed only), mysql_fetch_assoc() (keyed only), or use the extra argument on fetch_array to specify which you want: mysql_fetch_array($result, MYSQL_BOTH);
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.