php string to associative array - php

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)

Related

How to create json from array in php like APIs

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

Extract the value of a JSON with no keys on PHP

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.

PHP JSON Count values in same array

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

PHP Make a multidimensional array from one mysql Row's columns?

I have the following mysql db row.
id | user_id | title_1|desc_1|link_1|title_2|desc_2|link_2|
and so on up to 10
from this one row I want to remove id and user id and have the resulting multidimensional array.
the main issue is iterarating over the associative array that is returned by my query and splitting it up into arrays of 3.
Array = (
[0] = array (
[tite_1] => 'sometitle'
[desc_1] => 'description'
[link_1] => 'a link'
)
[1] = array (
[tite_2] => 'sometitle'
[desc_2] => 'description'
[link_2] => 'a link'
)
and so on how can I achieve this I am stumped!!?
You probably want to structure your table into two tables like this:
parent(id, user_id, more_fields, whatever_you_need_here)
child(parent_id, title, desc, link)
Now it'll be very easy to get the data that you want to have.
SELECT title, desc, link FROM child WHERE parent_id = 12;
Of course, parent and child should be named appropriately, e.g. user and links.
The correct answer would be to redesign your database to use 3rd normal form. You should probably drop everything and read up on database normalization before you do anything further.
A proper design would be something like:
CREATE TABLE user_has_links (
id INT PRIMARY KEY,
user_id INT,
title TEXT,
description TEXT,
link TEXT
)
To store multiple links per user, you would simply create a new row in this table per link.
The real solution here is to fix your database to normalize these columns into other tables. However, if you are not in a position to fix your database, this code will do the job:
// $output will hold your full result set
$output = array();
while ($row = mysql_fetch_assoc($result)) {
// For each row returned, add a new array to $output
$output[] = array(
// The new array consists of 10 sub-arrays with the correct
// keys and values
array (
"title"=>$row['title1'],
"desc"=>$row['desc1'],
"link"=>$row['link1']
),
array (
"title"=>$row['title2'],
"desc"=>$row['desc2'],
"link"=>$row['link2']
),
...,
...,
array (
"title"=>$row['title10'],
"desc"=>$row['desc10'],
"link"=>$row['link10']
)
);
}

Tricky associative arrays in CodeIgniter

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)
);

Categories