I am currently using the jQuery plotting plugin (Click), but I am having trouble fetching the data out of my database.
I am using PHP for the SQL part, which returns an array like this:
Array (
[0] => 13
[id] => 13
[1] => 320.82
[real_value_1] => 320.82
)
Now I need it in the following format in order for the flot plugin to pick it up:
[13, 320.82]
But I am having trouble figuring out how.
This is the plotting code:
$(document).ready(function(){
var url = "view_json_graph.php?type=2";
$.get(url, function(data){
console.log(data);
$.plot($("#placeholder"), data, { yaxis: { max: 100 }, xaxis: { max: 100 } });
});
});
Where the javascript var data, would be the data returned ( [13, 320.82] ).
Could anyone please give me advice on how to do it? I've also looked into JSON, but I couldn't get it to work with JSON either.
You should simplify your array first, so it would only contain the values only once:
Array (
[0] => 13
[1] => 320.82
)
After that, you could use php's implode() function, to make your array into a string, separated by commas:
$result = '[' . implode( ',', $array ) . ']';
This will be your desired format.
Dont know whether the below code helps you
<?php
$sql = "SELECT id, value FROM sample";
$query = mysqli_query($connect, $sql);
while($res = mysqli_fetch_array($query))
{
$out[] = "[".$res[0].','.$res[1]."]";
}
$comma_separated = implode(",", $out);
echo $comma_separated;
?>
Related
I have a database of zip codes from The Zip Code Database Project that came as a .csv file. I converted it to json and it has no key for each array, they look like this:
[
{
"zipcode": 35004,
"state abbreviation": "AL",
"latitude": 33.606379,
"longitude": -86.50249,
"city": "Moody",
"state": "Alabama"
}
]
I have figured out how to search all of the arrays and locate a matching zip code but I can't figure out how to make that search return data about the array that it found it in.
I can search like this:
$filename = './assets/data/zips.json';
$data = file_get_contents($filename);
$zipCodes = json_decode($data);
$inputZip = 55555;
foreach ($zipCodes as $location) {
if ($inputZip == $location->zipcode) {
echo "Success";
}
}
Can anyone tell me how I can use this search (or a better idea) to store the latitude and longitude associated with the searched zip code to two variables? I have wasted nearly my whole weekend on this so any and all help is greatly appreciated.
Also, I have no issue using the raw csv file to perform this function, I just couldn't get as far as I did with json.
Thanks everyone!
To find out the index of an array by a property of the array items, use array_column to get just the values of that column/property, then use array_search to find the index.
<?php
$inputZip = 35004;
$index = array_search($inputZip, array_column($zipCodes, 'zipcode')); // 0
print_r($zipCodes[$index]); // the entire object
https://3v4l.org/TAXQq
Based on your code:
foreach ($zipCodes as $index => $location) { // index is a key
if ($inputZip == $location->zipcode) {
echo "Index is ".$index;
break;
}
}
var_dump($zipCodes[$index]);
I should note that it seems you are doing something wrong because you don`t suppose to store your data like this and loop through array all the time.
To get the keys of an array that is filtered due to certain parameters that must be met you could use array_keys and array_filter.
For Example
$array = [1,2,1,1,1,2,2,1,2,1];
$out = array_filter($array,function($v) {
return $v == 2;
});
print_r(array_keys($out));
Output
Array
(
[0] => 1
[1] => 5
[2] => 6
[3] => 8
)
Try the above example in PHP Sandbox
To match your actual data structure.
$json = '[{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35005,"state abbreviation": "AL","latitude": 33.606579,"longitude": -86.50649,"city": "Moody","state": "Alabama"}]';
$array = json_decode($json);
$out = array_filter($array, function($v) use ($inputZip) {
return $v->zipcode == $inputZip; // for the below output $inputZip=35004
});
print_r(array_keys($out));
Output
Array
(
[0] => 0
[1] => 1
)
Try the example in PHP Sandbox
I am trying to parse some javascript variables using PHP.
Random website: (not my website)
//.... content ...
function(response) {
if (response) {
var data = { id: "fka1q021", action: "post", date: "today" };
}
//.....
$url = 'www.website.com';
$content = htmlspecialchars(file_get_contents($url));
preg_match_all('/var data = { id: "(.*?)", action: "post", date: "today" };/', $content, $matches);
print_r($matches);
Output:
Array ( [0] => Array ( ) [1] => Array ( ) )
I want to get value of id which is fka1q021
How can I get it? Thanks
You may want to try preg_match instead of preg_match_all. Then, the $matches array will contain the entire matched expression as its 0th element, and the match within your parenthesized sub-expression as its 1st element. That 1st element is the id you're looking for.
So, try:
preg_match('/var data = { id: "(.*?)", action: "post", date: "today" };/', $content, $matches);
Here is full example code:
<?php
$content = <<<ENDOFCONTENT
//.... content ...
function(response) {
if (response) {
var data = { id: "fka1q021", action: "post", date: "today" };
}
//.....
ENDOFCONTENT;
preg_match('/var data = { id: "(.*?)", action: "post", date: "today" };/', $content, $matches);
print_r($matches);
print "id = " . $matches[1] . "\n";
Here is resulting output:
Array
(
[0] => var data = { id: "fka1q021", action: "post", date: "today" };
[1] => fka1q021
)
id = fka1q021
You are not getting anything with your regular expression, because you are applying htmlspecialchars to the content you are reading – and that replaces " with ", so your expression does not find the " you have in there.
Just remove htmlspecialchars, and your pattern will match.
Javascript is client side and PHP is server side, so all the PHP will have executed before the Javascript can run. See this question: How to pass JavaScript variables to PHP?
I'm not sure what your doing is legit... JS ans PHP doesn't execute at the same time and in the same place. Maybe you got this after an ajax call ?
Anyway, analysing a JS data with php can be done with json_decode. I think your problem here will be that json_decode won't understand {id:"value"}, he needs {"id":"value"} instead...
if ( preg_match("#data = ({[^}]*})#",$data,$matches) )
json_decode($matches[1]) ;
For example,
print_r(json_decode('{"id":"fka1q021","action":"post","date":"today"}') );
Render a php object :
stdClass Object
(
[id] => fka1q021
[action] => post
[date] => today
)
A very simple regex is
(?:id:\s(\".*?\"))
Debuggex Demo
then the id will be in capture group 1.
Let me know if you need a more complex regex. And if so, provide more info.
With fetchAll(PDO::FETCH_ASSOC) get such array
$array =
Array
(
[0] => Array
(
[FinalCurrencyRate] => 0.000062
)
)
Need to json_encode to use in
$.post("__02.php", { 'currency': currency }, function(data, success) {
$('#currency_load').html(data.FinalCurrencyRate);
$('#currency_load0').html(data.FinalCurrencyRate0);
$('#currency_load1').html(data.FinalCurrencyRate1);//and so on
}, "json");
If simply echo json_encode($array); then does not work.
Need to convert to json format array like this:
$arr = array ('FinalCurrencyRate'=>"0.000062");
To convert to json format, wrote such code
$json_array = "{";
$flag_comma = 0;
foreach($array as $i =>$array_modified) {
if ($flag_comma == 0) {
$json_array .="'FinalCurrencyRate". $i."'=>'". $array_modified[FinalCurrencyRate]. "'";
$flag_comma = 1;
}
else {
$json_array .=", 'FinalCurrencyRate". $i."'=>'". $array_modified[FinalCurrencyRate]. "'";
}
}
$json_array .= "}";
Then echo json_encode($json_array);. And only one echo json_encode.
But does not work.
Understand that there are errors in code to convert to json format. What need to correct, please?
If I understand correctly you just want to return the first row form your array, then you just need to do this
echo json_encode($array[0]);
UPDATE
I think I see what you're trying to do now, you're trying to append the index to the FinalCurrencyRate key in each row. No need to do that, what you should do is change your javascript code to look like this:
$('#currency_load0').html(data[0].FinalCurrencyRate);
$('#currency_load1').html(data[1].FinalCurrencyRate);//and so on
I'm having problems translating my associative array that I create in jQuery to something I can access and use in PHP.
I use the following to build an associate array:
var colors = {};
$(this).find('input[name="color_id"]').each(function() {
var color_entry_id = $(this).val();
colors[color_entry_id] = jQuery.makeArray($(this).siblings(".colors." + $(this).val()).find(".img_color a.selected").map(function() {
return $(this).css("background-color");
}));
});
Basically, the above code should return something of the form:
colors = {
"{{ color_entry_id }}": [array of string rgb values]
}
I then send it to my PHP script with the following:
$.post(
"test.php",
{ "edit_colors": JSON.stringify(colors) },
...
);
In my PHP, I want to be able to grab the array corresponding to a {{ color_entry_id }} and loop through the values to use in an update query. The following is my PHP code:
$check_colors = array(
"rgb(204, 51, 51)" => "red",
"rgb(102, 153, 204)" => "sky_blue",
"rgb(0, 204, 51)" => "lime_green",
"rgb(0, 102, 0)" => "dark_green",
"rgb(153, 0, 0)" => "burgandy",
"rgb(255, 102, 51)" => "orange",
...
);
$colors = json_decode($_POST['edit_colors']);
foreach($images as $color_entry => $image_link) {
$update_color_query = "UPDATE color SET ";
foreach(array_keys($check_colors) as $color) {
if(in_array($color, $colors[$color_entry])) {
$update_color_query .= $check_colors[$color] . "=1, ";
} else {
$update_color_query .= $check_colors[$color] . "=0, ";
}
}
$update_color_query .= "image_url='$image_link' WHERE id=$color_entry";
mysql_query($update_color_query);
}
In the above code, images is a separate array with corresponding {{ color_entry_id }}s and image links as well. $check_colors is a PHP hardcoded associative array of rgb values to human readable colors. My problem is that the link:
in_array($color, $colors[$color_entry])
throws a "Fatal error: cannot use type stdClass as array" because $colors[$color_entry] is not becoming the two dimensional array I'm trying to get it to be. So anyone know what I am doing wrong and how I can get this two dimensional array to loop through in my PHP code?
The error is exactly what it says: You can't use an OBJECT as an ARRAY. When you use json_decode, it defaults to an object. You need it to be an associative array.
So change it to this:
$colors = json_decode($_POST['edit_colors'], true);
Now, you can iterate through $colors as you need.
I am trying this new method I've seen serializeArray().
//with ajax
var data = $("#form :input").serializeArray();
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
So I get these key value pairs, but how do I access them with PHP?
I thought I needed to do this, but it won't work:
// in PHP script
$data = json_decode($_POST['data'], true);
var_dump($data);// will return NULL?
Thanks, Richard
Like Gumbo suggested, you are likely not processing the return value of json_decode.
Try
$data = json_decode($_POST['data'], true);
var_dump($data);
If $data does not contain the expected data, then var_dump($_POST); to see what the Ajax call did post to your script. Might be you are trying to access the JSON from the wrong key.
EDIT
Actually, you should make sure that you are really sending JSON in the first place :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Ready to be encoded is not JSON. Apparently, there is no Object2JSON function in jQuery so either use https://github.com/douglascrockford/JSON-js/blob/master/json2.js as a 3rd party lib or use http://api.jquery.com/serialize/ instead.
The OP could have actually still used serializeArray() instead of just serialize() by making the following changes:
//JS
var data = $("#form :input").serializeArray();
data = JSON.stringify(data);
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
// PHP
$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array
its possible by using the serialize array and json_decode()
// js
var dats = JSON.stringify($(this).serializeArray());
data: { values : dats } // ajax call
//PHP
$value = (json_decode(stripslashes($_REQUEST['values']), true));
the values are received as an array
each value can be retrieved using $value[0]['value'] each html component name is given as $value[0]['name']
print_r($value) //gives the following result
Array ( [0] => Array ( [name] => name [value] => Test ) [1] => Array ( [name] => exhibitor_id [value] => 36 ) [2] => Array ( [name] => email [value] => test#gmail.com ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) )
The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify" it. See this for more info:
http://www.tutorialspoint.com/jquery/ajax-serializearray.htm
I have a very similar situation to this and I believe that Ty W has the correct answer. I'll include an example of my code, just in case there are enough differences to change the result, but it seems as though you can just use the posted values as you normally would in php.
// Javascript
$('#form-name').submit(function(evt){
var data = $(this).serializeArray();
$.ajax({ ...etc...
// PHP
echo $_POST['fieldName'];
This is a really simplified example, but I think the key point is that you don't want to use the json_decode() method as it probably produces unwanted output.
the javascript doesn't change the way that the values get posted does it? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here']
edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST). That would give you some idea about what you'd need to do in PHP to access the data you need.
Maybe it will help those who are looking :)
You send data like this:
$.ajax({
url: 'url_name',
data: {
form_data: $('#form').serialize(),
},
dataType: 'json',
method: 'POST'
})
console.log($('#form').serialize()) //'f_ctrType=5&f_status=2&f_createdAt=2022/02/24&f_participants=1700'
Then on the server side use parse_str( $_POST['form_data'], $res).
Then the variable $res will contain the following:
Array
(
[f_ctrType] => 5
[f_status] => 2
[f_createdAt] => '2022/02/24'
[f_participants] => 1700
)
You can use this function in php to reverse serializeArray().
<?php
function serializeToArray($data){
foreach ($data as $d) {
if( substr($d["name"], -1) == "]" ){
$d["name"] = explode("[", str_replace("]", "", $d["name"]));
switch (sizeof($d["name"])) {
case 2:
$a[$d["name"][0]][$d["name"][1]] = $d["value"];
break;
case 3:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]] = $d["value"];
break;
case 4:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]][$d["name"][3]] = $d["value"];
break;
}
}else{
$a[$d["name"]] = $d["value"];
} // if
} // foreach
return $a;
}
?>