Extract the value of a JSON with no keys on PHP - 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.

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

PHP: Object of class Closure could not be converted to int

I have a problem using the usort function. My array has the following model :
Fusion
|
| Array_1
| |
| | Array_1_1
| | | clock => "08:08"
| | | //Other fields
| | |
| |
| | Array_1_2
| | | clock => "04:51"
| | | //Other fields
| | |
|
| Array_2
| ...
I want to sort the arrays in Array_X basing on the 'clock' field. I made this code, basing on the PHP documentation of usort (4th example) :
foreach ($fusion as $fus){
usort($fus,function ($key = 'clock'){
return function ($a,$b) use ($key){
return strnatcmp($a[$key],$b[$key]);
};
});
}
... but it returns the following exception :
Object of class Closure could not be converted to int
Do you have any idea ? Thanks for your help.
You're trying to pass the following as a callback (2nd argument of usort)
function ($key = 'clock'){
return function ($a,$b) use ($key){
return strnatcmp($a[$key],$b[$key]);
};
}
But the documentation clearly specifies that
The comparison function must return an integer [...]
However, your callback returns another closure. This is why you get a Closure to int convertion Exception.
I believe what you're trying to do is to execute the inner-closure to get the final callback using the right values. I'd say this is useless because, unlike in Javascript, php closures are opt-in, not all-in, which means their context must be included with use the way you did for $key in the outer-closure.
You could simply do:
$key = 'clock';
foreach ($fusion as $fus){
usort($fus,function ($a,$b) use ($key){
return strnatcmp($a[$key],$b[$key]);
});
}
And if $key comes from some other kind of context you may just have to adjust the variable assignment.
Convert your object into an array using get_object_vars($object) first.
If the object that you are getting is generated by a different function, then read documentation for that function and find a way for it to return an array instead of object.
Examples and documentation can be found here http://php.net/manual/en/function.get-object-vars.php

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 string to associative array

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)

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