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
Related
I have a sample 2018 student pass record of CSV file like this...
1 | Jonathan | 4CS-10 | 1,2,3,4 | Pass with credit
2 | Peter Jo | 4CS-11 | 1,2,3,4 | Pass with credit
and I want to convert it into Json. So firstly I thought I need to change it into php array and then i have to use json_encode function.
I have fetched CSV data into array with fgetcsv().
The final json result I want to achieve is the following:
{"2018" : {
"4CS-10" : {
"name" : "Jonathan",
"destinations": "1,2,3,4"
},
"4CS-11" : {
"name" : "Peter Joe",
"destinations": "1,2,3,4"
}
}
}
To produce that structure you need to iterate your CSV array and transform the rows to associative arrays, then add each row to your output array using the second column as a key.
foreach ($your_array as $row) {
// ↓ use 4CS-10, etc. as keys
$data[$row[2]] = ['name' => $row[1], 'destinations' => $row[3]];
// convert numeric keys ↑ to string keys ↑
}
echo json_encode(['2018' => $data]);
You may have trouble with this if the column you're using as key (values like 4CS-10, etc.) is not unique. If any values there are repeated, you'll only get the last row from the CSV because you'll overwrite the original value of that key. If that's the case, you'll need to change your structure a little if you want to get all the data, and make the value under 4CS-10 an array of objects instead of a single object.
$data[$row[2]][] = ['name' => $row[1], 'destinations' => $row[3]];
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'm looking at creating a 'Multi Page Navigation System' using PHP and MySQL along with jQuery.
Ideally, what I want is to be a a list of items, such as:
* Item 1
* Item 2
* Item 3
Within Item 1, there is 3 other subcategories, within Item 2 there are 2 subcategories and within them 2 subcategories there are 3 more subcategories
So what I'm really looking for is the following:
1) when i click on 'Item 2` is displays the 2 subcategories
2) when I click on one of these subcategories it displays the 3 others
Ideally, I'd like to do this in using AJAX as I'd like this to be in a jQuery UI Dialog.
I have 2 tables:
category
id | title
----------
1 | item 1
2 | item 2
3 | item 3
subcategory (simplified)
id | cat_id | parent_id | title
-------------------------------
1 | 1 | 0 | subcat1
2 | 1 | 0 | subcat2
3 | 1 | 1 | subcat1_subcat1
4 | 1 | 1 | subcat1_subcat2
5 | 1 | 1 | subcat1_subcat3
My main issue is how I'd go about doing this?
I don't really want to have a big array with all that data in, as it could potentially have more categories and subcategories.
Does any have an idea what would be the best solution to about this?
Thanks
What's wrong with having it all stored in an array? Unless you're planning on have thousands of elements in those menu items (which would be incredibly un-user-friendly), then it's just a walk in the park for PHP.
Also, you might want to be abit more specific about what your requirement is. Is it the jQuery, the PHP or both? Do you need the code or the concept?
EDIT: Solution
So based on the comments you listed, here's a proof of concept.
PHP:
You'll need to read from the Database and load them into an array. That's pretty easy to do with PDO. Just use the fetchAll() command and retrieve the entire result set in an associative array. The tricky part becomes converting your 'flat' DB into a multi-dimensional array. Here goes:
// Retrieve the details from the database in the $rows associative array
...
// Now, we need to expand the 'flat' DB structure into a multi-
// dimensional array.
$multid=findKids($rows);
// Send it back, JSON-encoded
die(json_encode(
'result' => 'success',
'response' => $multid
)); // Send the response back via AJAX
/**
* Here's the function that converts the flat DB into a multi-
* dimensional array. It tracks all the parents in a single
* array and collects the kids for those parents. If it comes
* across a new parent, if fetches all the kids recursively.
*/
function findKids( $rows, $parentid=NULL, &$parents=NULL ) {
// Create a temporary array for the kids
$shelter;
// Go through all the rows
foreach($rows as $index => $row) {
// Find the kids that belong to this parent
if($row['parentid']==$parentid) {
// This kid belongs to this parent
// Move it to the temporary shelter
$shelter[$parentid][]=$row;
}
else {
// This kid doesn't belong to this parent.
// Have we already talked to the parent before?
if(isset($parents[$row['parentid']])) {
// Yes, the parent has already been visited. Ignore
}
else {
// Parent hasn't been visited; add it
$shelter[$row['parentid']][]=findKids($rows,$row['parentid'],$parents);
}
} // close else{ }
} // close foreach{ }
// Return the shelter, with all the kids
return $shelter;
}
The returned array will include a response that looks like this:
$response=[
'result'=>'success',
'response'=>[
0=>[ // Contains the kids for $parentid=0
['id'=>1, 'cat_id'=>1, 'parent_id'=>0],
['id'=>2, 'cat_id'=>1, 'parent_id'=>0]
],
1=>[ // Contains the kids for $parentid=1
['id'=>3, 'cat_id'=>1, 'parent_id'=>1],
['id'=>4, 'cat_id'=>1, 'parent_id'=>1],
['id'=>5, 'cat_id'=>1, 'parent_id'=>1]
],
]
];
jQuery: You'll interpret the JSON response and iterate through the response to create the menu on the fly.
Here's a sample script that'll display the array as a nested unordered list.
// Call the printMyFamily method on the element to display
// that you'd like to see the menu appear in
$outputElem.html($.printMyFamily(NULL,response['response']));
$.printMyFamily = function(parentid,haystack){
// Our output variable
output="<ul>";
// Find the kids
$haystack.each(function(index,elem){
// Is this kid ours?
if(elem[parentid] == parentid){
// Yes. Add to output
output+="<li id='"+elem['id']+"'>"+elem['catid']+"</li>";
// Find this items kids (if any)
output+=$.printMyFamily(elem['id'],haystack);
}
else { /* not ours, ignore */ }
});
// Is the result an empty string? If so, just clear it
if(output=="<ul>"){ output=""; }
// Return the output
return output;
};
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)
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)
);