I'm trying to make a bar chart for a mobile devices that submit data. Every minute, each mobile device sends a packet of data to the web server - where it's then stored in a MySQL database. Each mobile device is assigned an IP addresses, and each IP address can send data multiple times a minute (sometimes as many as 10). Here is what an example table would look like:
date_received | bytes | IP address
----------------------------------
1314831600 | 100 | 1482747555
1314831600 | 990 | 1482747555
1314831600 | 074 | 1482747555
1314831660 | 420 | 1482747555
1314831660 | 183 | 1482747555
So you can see that one IP address can submit multiple times a minute over a span of hours (therefore multiple minutes). How would I create an associative array that looked like this:
array
(
1314831600 = array
(
1482747555 => 100,
1482747555 => 990,
1482747555 => 074
);
1314831660 = array
(
1482747555 => 420,
1482747555 => 183
);
);
The first key would be the date_received value, and the the IP addresses which are sent for that time (with their corresponding bytes values). I'm using CodeIgniter and I thought about populating arrays in my foreach database loop, but wasn't quite sure how best to do this. Does anybody have any advice?
N.B: I need to keep database calls to a minimum because some tables contain hundreds of thousands of values.
You cannot share array keys like that (ip address) as they will be overwritten. You can do something like:
$packets = array();
while ($row = mysql_fetch_assoc($res)) {
$packets[$row['date_received']][] =
array('ip_address'=>$row['ip_address'],
'bytes'=>$row['bytes']
);
}
Then you can loop through the data with:
foreach ($packets as $date => $info) {
echo "date = $date, ip = $info[ip_address], bytes = $info[bytes]";
}
If you rewrite part of your array like this, the problem becomes much easier for you:
array
(
1482747555 => array(100,990,074)
);
Related
I'm trying to extract the value of a JSON, without a key that gives me a reference.
This is my JSON code:
{"StatTrak™ Dual Berettas | Dualing Dragons (Battle-Scarred)":0.37,"★ StatTrak™ Huntsman Knife | Scorched (Well-Worn)":101.65,"Sticker | iBUYPOWER | DreamHack 2014":11.34,"MP9 | Sand Dashed (Well-Worn)":0.03,"★ Flip Knife | Urban Masked (Field-Tested)":61.74}
The first value is the name and the second one the price. I've got a very long JSON with a lot of name's and prices.
name="StatTrak™ Dual Berettas | Dualing Dragons (Battle-Scarred)"<br>
price="0.37"
Actually don't know how to access the name to extract the other value.
I have the name of the weapons saved on my site from another API. I have to extract the value of this JSON and compare that name with the name the API gave me previously.
The name is the key:
$array = json_decode($json, true);
foreach($array as $name => $price) {
echo "$name<br>$price<br>";
}
You see it with a print_r($array):
Array
(
[StatTrakΓäó Dual Berettas | Dualing Dragons (Battle-Scarred)] => 0.37
[Γÿà StatTrakΓäó Huntsman Knife | Scorched (Well-Worn)] => 101.65
[Sticker | iBUYPOWER | DreamHack 2014] => 11.34
[MP9 | Sand Dashed (Well-Worn)] => 0.03
[Γÿà Flip Knife | Urban Masked (Field-Tested)] => 61.74
)
Assuming I understood you correctly and you want to access values by keys:
First of all, I'd axtually recommend using Javascript for this. It doesn't seem like you're parsing any personal or important data that should remain private, so why not let the client do the work instead of giving your server more work to do?
Anyhow, as for PHP:
First you'll need to decode the json string using the json_decode() function, giving it 2 parameters - the first will be the json string, and the second a simple true boolean, so that it will return an array instead of a json object. The function returns an array, in which each key and value correspond to the name and price in the json list, with the name being the key. Than, to access the value, simply use the array value by key functionality ($arr['weaponname'] would return the price of 'weaponnane', assuming it exists [otherwise you'll get an exception], so you'll need to check that using isset() or array_key_exists()).
Put together, you'll have something along the lines of the following (you'll obviously need to modify this to fit your needs), assuming $weaponname contains the weapon name and $jsonstring the json string:
$price = NULL;
$jsonarr = json_decode($jsonstring, true);
if (isset($jsonarr[$weaponname]))
{
$price = $jsonarr[$weaponname];
}
If the weapon doesn't exist or it's price is NULL in the array, the $price variable will be NULL.
I'll note that this is a very special case, hence the question to begin with. Under normal circumstances, such a function would be simple:
I have an array named $post_id, which contains 5 values
(Each numerical)
In order to print each value in the array, I use the following loop:
.
for ($i = 0; $i < $num; $i++)
{
echo $post_id[$i] . ' ';
}
...Which prints the following: 49, 48, 47, 46, 43
3. In my database, I have a table that looks like this:
post_categories
_____________________
post_id | category
__________|__________
43 | puppies
43 | trucks
46 | sports
46 | rio
46 | dolphins
49 | fifa
4. So, using the data in the array $post_id, I'd like to loop a database query to retrieve each value in the category column from the post_categories table, and place them into uniquely named arrays based on the "post id", so that something like...
echo $post_id_49[0] . ' ', $post_id_46[1];
...Would print "fifa rio", assuming you use the above table.
An example of such a query:
//Note - This is "false" markup, you'll find out why below
for ($i = 0; $i < $num; $i++)
{
$query = "SELECT category FROM post_categories WHERE post_id = $post_id[$i]";
fakeMarkup_executeQuery($query);
}
Why is this a "special" case? For the same reason the above query is "false".
To elaborate, I'm working inside of a software package that doesn't allow for "normal" queries so to say, it uses it's own query markup so that the same code can work with multiple database types, leaving it up to the user to specify their database type which leaves the program to interpret the query according to the type of database. It does, however, allow the query to be stored in the same "form" that all queries are, like "$result = *query here*" (With the only difference being that it executes itself).
For that reason, functions such as mysql_fetch_array (Or any MySQL/MySQLi function akin to that) cannot, and will not work. The software does not provide any form of built in alternatives either, effectively leaving the user to invent their own methods to achieve the same results. I know, pretty lame.
So, this is where I'm stuck. As you'd expect, all and any information you find on the Internet assumes you can use these MySQL & MySQLi functions. What I need, is an alternative method to grab one array from the results of a looped query per loop. I simply cannot come to any conclusion that actually works.
tl;dr I need to be able to (1) loop a query, (2) get the output from each loop as it's own array with it's own name, and (3), do so without the use of functions like mysql_fetch_array. The query itself does not actually matter, so don't focus on that. I know what do with the query.
I understand this is horrifically confusing, long, and complicated. I've been trudging through this mess for days - Close to the point of "cheating" and storing the data I'm trying to get here as raw code in the database. Bad practice, but sure as heck a lot easier on my aching mind.
I salute any brave soul who attempts to unravel this mess, good luck. If this is genuinely impossible, let me know so that I can send the software devs an angry letter. All I can guess is that they never considered that a case like mine would come up. Maybe this is much more simple then I make it to be, but regardless, I personally cannot come to an logical conclusion.
Additional note: I had to rewrite this twice due to some un explained error eliminating it. For the sake of my own sanity, I'm going to take a break after posting, so I may not be able to answer any follow up questions right away. Refer to the tl;dr for the simplest explanation of my need.
Sure you can do this , here ( assuming $post_ids is an array of post_id that you stated you had in the OP ), can I then assume that I could get category in a similar array with a similar query?
I don't see why you couldn't simply do this.
$post_id = array(49, 48, 47, 46, 43);
$result = array();
foreach($post_id as $id)
{
//without knowing the data returned i cant write exact code, what is returned?
$query = "SELECT category FROM post_categories WHERE post_id = $id";
$cats = fakeMarkup_executeQuery($query);
if(!empty($cats)) {
if(!isset($result[$id])){
$result[$id] = array();
}
foreach( $cats as $cat ){
$result[$id][] => $cat;
}
}
}
Output should be.
Array
(
[49] => Array
(
[0] => fifa
)
[46] => Array
(
[0] => sports
[1] => rio
[2] => dolphins
)
[43] => Array
(
[0] => puppies
[1] => trucks
)
)
Ok, assuming you can run a function (we'll call it find select) that accepts your query / ID and returns an array (list of rows) of associative arrays of column names to values (row), try this...
$post_categories = [];
foreach ($post_id as $id) {
$rows = select("SOME QUERY WHERE post_id = $id");
/*
for example, for $id = 46
$rows = [
['category' => 'sports'],
['category' => 'rio'],
['category' => 'dolphins']
];
*/
if ($rows) { // check for empty / no records found
$post_categories[$id] = array_map(function($row) {
return $row['category'];
}, $rows);
}
}
This will result in something like the following array...
Array
(
[49] => Array
(
[0] => fifa
)
[46] => Array
(
[0] => sports
[1] => rio
[2] => dolphins
)
[43] => Array
(
[0] => puppies
[1] => trucks
)
)
I have a json object in my php script that was encoded using the json_encode php function.
Here is the object when var_dumped...
string '{"voting_sys":"50","beta_site":"50"}' (length=36)
string '{"voting_sys":"50","beta_site":"50"}' (length=36)
Database structure:
My goal is to get the sum of the values in the voting_sys for each user, and in the beta_site...this is going to be used for voting, but on an unknown amount of features/values.
Any ideas? I have tried the following...
$voters = DB::table('votes')->get();
foreach($voters as $vote){
$vote_array[$voter->user_id]=json_decode($voter->value, true);
}
var_dump($vote_array);
This returns the decoded json object to the array.
I would assign the "voting_sys" as the key for the array, and then the integer value to the value of the array, but there will be an unknown number of features. In this example, there are only two features the users can vote on, but there may be more at a later date. I use the feature ID to roll out a new set of features the users can vote on.
I am using Laravel 4.1
[Edit: Result]
$feature_list = DB::table('features')->where('rev_id', Config::get('app.beta_rev'))->get();
$feature_array=array();
foreach ($feature_list as $feature){
array_push($feature_array, $feature->name);
}
foreach($feature_array as $feature){
$voters = DB::table('votes')
->select(DB::raw('sum(value)'))
->where('feature_name', '=', $feature)
->get();
echo $feature.' - ';
var_dump($voters);
echo '<br />';
}
which when called, dumps:
voting_sys -
array (size=1)
0 =>
object(stdClass)[248]
public 'sum(value)' => string '149' (length=3)
beta_site -
array (size=1)
0 =>
object(stdClass)[249]
public 'sum(value)' => string '69' (length=2)
Which is exactly correct for the votes I entered. Thanks for the help.
I would suggest using a slightly different database structure. It is almost never a good idea to serialize / json_encode data in your database. Since you already have a dedicated table for votes it should be simple to change your table from what you curretly have to the following:
id | user_id | feature | value
------------------------------
1 | 2 | sys | 50
2 | 2 | beta | 40
3 | 3 | sys | 50
This would make counting very trivial:
SELECT SUM(value) FROM table WHERE feature = 'sys'
Use array_sum
array_sum — Calculate the sum of values in an array
$voters = DB::table('votes')->get(); // get the JSON response response
$jsonDecodedArray = json_decode($voters,true); // decode the JSON
$sum = array_sum($jsonDecodedArray); // Use php array_sum
I currently have a script that parses a text file with (for example) 100 lines, from 10 different users, and for each line pulls out a $userName, $timestamp and a variety of other things. Is there a way that I can loop through (after it does the parsing) and work with 1 group of $userName at a time.
The end goal is to enter the data into google docs 1 user at a time.
I have tried using $i and $i++ however due to the fact that my primary loop is an array within an array things get a little goofy.
What I would like is the ability to see the following
$userName | $timeStamp
mhopkins321 | 13-12-30
mhopkins321 | 14-59-01
mhopkins321 | 19-32-59
You just have to make the proper array structure:
$users = array(
'mhopkins321' => array(
'13-12-30',
'14-59-01',
...
),
'anotherUser' => array(
...
)
);
So when you're parsing, and run into a username and timestamp:
$users[$username][] = $timestamp;
And when you want to make that table
foreach($users as $user) {
foreach ($user as $timestamp) {
echo $user."| ".$timestamp."\n";
}
}
...probably with better formatting, but there ya go.
I'm trying to store a set of data in a TEXT field in my MySQL database. The data to store are as follow (data format is not fixed yet):
[location1] => (lat,lon,zoom)
[location2] => (lat,lon,zoom)
[location3] => (lat,lon,zoom)
etc...
In the end all these data will be one single string. How should I write/format this string so that I can then use it in PHP as a regular associative array?
Why don't you save them in an individual table with this scheme:
Foreign key | Location (text) | lat (double) | lon (double) | zoom (double)