I've got an array with different "columns", for example: id, title, date, data etc.
It is a JSON array.
The data element has multiple entries:
"data":["test = test", "2nd test", "3rd test"]
How can I find how many entries there are in the "data" element of the "result" array?
When I try result.data.length, it gives me the whole length, so all the characters.
Here, it would say something like 27, while I want 3 as an answer.
EDIT: this is how I get the elements and push them (I get a JSON array):
$.getJSON("test.php?id=" + id, function(data) {
$.each(data, function(index, data1) {
window.result.push(data1);
});
And this is the test.php code:
if(isset($_GET['id'])){
$id = $_GET['id'];
$liste = getData($id);
$arr = array();
$i = 0;
foreach($liste as $result){
$arr[$i]['id'] = $result->id();
$arr[$i]['titre'] = $result->titre();
$arr[$i]['data'] = $result->listeMot();
$i++;
}
echo json_encode($arr);
Thanks for the help.
The answer was finally found (thanks a lot to #RocketHamzat).
It was indeed a string, and not an array. In that case, I had returns after each pair of words (I thought they were separated by commas, but they weren't).
So, to count, this is what I did:
result.data.split('\r\n').length;
This worked like a charm. Thanks for your help!
I agree with the comments posted - your return object does not look as if it is formatted properly. data should be an object with a key value of the array. Your return should look like the following:
var d = '{"data":["test = test", "2nd test", "3rd test"]}';
console.dir(JSON.parse(d));
var arr = JSON.parse(d);
console.log(arr.data.length);
The console.dir will display the object, and the console.log displays a length of 3.
Are you formatting the response as a JSON string manually? If so wrap with {}
Hope that helps.
Related
I'm trying to refresh the content of my cells of an table. Therefore, I have a JavaScript which contains an AJAX request to a .php file, which creates my content that I want to insert into my table via JavaScript. The .php files last command is something like echo json_encode($result);.
Back in the JavaScript it says:
var testarray = xmlhttp.response;
alert(testarray);
But the outut from the alert looks like:
{"1":{"1":"3","2":"0","3":"2","4":"0"}}{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}...
So it seems the variable testarray isn't handled as an array but as a string. I already tried var testarray = JSON.parse(xmlhttp.response), but this doesn’t work. Neither does eval() works.
I don't know what to do, so the response of my request becomes an object.
There are 2 strange things in your json:
this part is not json valid: ...}{...
two object should be separated by comas
The notation is object with string indexes not array with int indexes
it should be something like: [[1,2,3,4],[5,6,7,8]]
for the point 1. it looks like you have a loop that concatenate many json
for the point 2. the object notation can be used as an array so it doesn't matter
Some code:
//the folowing code doesn't work: }{ is not parsable
var a=JSON.parse('{"1":{"1":"3","2":"0","3":"2","4":"0"}}{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}');
//the folowing code work and the object can be used as an array
var a=JSON.parse('{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}');
alert(JSON.stringify(a[1]));
//the folowing code displays the real notation of a javascript array:
alert(JSON.stringify([1,2,3,4]));
I think that the problem here might be that your arrays do not have index 0.
e.g. if you output this from the server - it would produce an object:
$result = [];
for ($i = 1; $i < 5; $i++) $result[$i] = $i;
echo json_encode($result); // outputs an object
if you output this from the server - it would produce an array:
$result = [];
for ($i = 0; $i < 5; $i++) $result[$i] = $i;
echo json_encode($result); // produces an array
Anyways, even if your server outputs array as object - you should still be able to access it normally in javascript:
var resp = xmlhttp.responseText, // "responseText" - if you're using native js XHR
arr = JSON.parse(resp); // should give you an object
console.log(arr[1]); // should give you the first element of that object
I'm trying to simply echo a JSON object literal which includes every row in my database table.
As standard with the methods found in many other similar questions I looked at, I'm fetching every row and encoding it like so:
$con=mysqli_connect("localhost","username","pass","markers");//markers is db table name
$result = mysqli_query($con,"SELECT * FROM markers");
$rows = array();
while($r = mysqli_fetch_array($result))
{
$rows[] = $r
//or: $rows[] = array('data' => $r);
}
echo json_encode($rows);
Similarly to the question PHP: can't encode json with multiple rows or mysql table to json ,
I want to echo a JSON Object which looks like this:
{
"data1": // how do I get "data1"?
{
name: John Smith,
title: Mr,
description: a man
}
}
{
"data2":{ // how do I get "data2"?
name:Bob Smith,
title: Mr,
description: another guy
}
}
Except I do not get how to achieve the "headers", the titles of the first level string of objects, such as "data1" or data2". In fact, my database table doesn't necessarily even have those values/that column.
This is what it looks like right now:
How can I get simply numerical "headers" like "1", "2" or "data1", "data2" without having to designate the "name" column as the "headers"? (Or do I have to have a column for that?)
My goal is to process the values in every "row" in the returned JSON.
I plan to use the jQ $.each function $.each(data, function(dataNum, dataInfo) -- e.g. data1 would be passed to dataNum and the values would be passed to dataInfo -- and be able to access specific table values by dataInfo.name, which right now is not working.
Thanks to any help in advance!
I would think you are way better off using mysqli_fetch_object() to get each row as it own object. When you then json_encode $rows you would have an array of objects.
Here is the code:
$con=mysqli_connect("localhost","username","pass","markers");//markers is db table name
$result = mysqli_query($con,"SELECT * FROM markers");
$rows = array();
while($r = mysqli_fetch_object($result))
{
$rows[] = $r;
}
echo json_encode($rows);
Your JSON would look like this:
[
{
"name":"Some Name",
"title":"Some Title",
"description":"Some description"
},
{
"name":"Some Other Name",
"title":"Some Other Title",
"description":"Some other description"
},
...
]
In javascript, that gives you an integer-indexed array of objects. So your javascript might look like this:
var array = JSON.parse(jsonString);
$.each(array, function(key, value) {
alert(key); // numerical index
alert(value.name); // name
alert(value.title); // title
alert(value.description); // description
});
Create indexes in your $rows variable:
<?php
$t['a'] = array ('name' => 'foo');
$t['b'] = array ('name' => 'bar');
echo json_encode ($t);
?>
In your case, a simple integer should do the trick, or something like $rows['data' . $i] followed by a $i++.
I have a JSONArray generated in java and I post it to one of my PHP files where it's saved to a file. From there it gets read and I need to generate a chart based on this data. All I need is to convert my raw JSON which has values I don't need, into a simply php array.
[{"id":1,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"},{"id":2,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"}]
Is an example of 2 elements inside my JSON array. What I need todo is filter those values into arrays accordingly.
For example get how many votes a 'player' has, I need to add up how ever many elements are in the JSONArray, because 1 element is 1 vote (the id is primary auto-increment in my mysql DB, not located on my webserver)
I'd like the array to be to [player, votes] so when I echo the array it will be easily parsed by the google chart tools I'm using. I've spent the last 5 hours working on this and I've been stuck, thanks for any help!
To decode the JSON into a php array, you can do:
$json_array = json_decode($raw_json);
Then, to get the number of votes for each player out of the array:
$player_votes = array_reduce($json_array,
function($v, $item) {
if(!array_key_exists($item->player, $v))
$v[$item->player] = 1;
else
$v[$item->player] = 1 + $v[$item->player];
return $v;
}, array());
If I understand your question correctly, this will work.
EDIT: Updated the second code snippet
Try this :
$str = '[{"id":1,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"},{"id":2,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"}]';
$res = array();
foreach(json_decode($str,true) as $val){
if(array_key_exists($val['player'],$res)){
$res[$val['player']] = $res[$val['player']]+1;
}
else{
$res[$val['player']] = 1;
}
}
echo "<pre>";
print_r($res);
Output :
Array
(
[Orangeguy24] => 2
)
I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/
I have a JSON array that looks like this:
[{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"23-08-2011"},{"RegDate":"07-09-2011"},{"RegDate":"09-09-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"03-11-2011"},{"RegDate":"03-11-2011"},{"RegDate":"11-11-2011"},{"RegDate":"16-11-2011"},{"RegDate":"18-11-2011"},{"RegDate":"21-11-2011"},{"RegDate":"02-12-2011"},{"RegDate":"02-12-2011"},{"RegDate":"12-12-2011"}]
The code to get this json array is as of the following:
var unavailableDates1 = jQuery.parseJSON('<?php echo json_encode($noticesDates) ?>');
I am trying too get all of the dates in that array (which was originally a multidimensional array), and put it inside one array:
var unavailableDates = ["9-3-2012", "14-3-2012", "15-3-2012"]; for example
I am unsure of how to do this, I have tried a foreach but wasn't successful.
All help will be appreciated.
First of all, that parseJSON is unnecessary and actually dangerous. Take it out:
var unavailableDates1 = <?php echo json_encode($noticesDates) ?>;
Then, just use jQuery.map:
var unavailableDates = $.map(unavailableDates1, function(item) {
return item.RegDate;
});
Using a string like that is dangerous for the following three objects, for example:
{"key":"Backslash here: \\"}
{"key":"I'm a horse!"}
{"key":"Some\\backslash"}
They become, respectively:
SyntaxError: Unexpected end of input (Single escape escapes end of string)
SyntaxError: Unexpected identifier (Unescaped single quote breaks out of the string, actually an XSS vulnerability)
Object
key: "Someackslash" (\\b becomes the \b backspace control character)
__proto__: Object
You could escape it again, but there's no need; valid JSON is always a valid JavaScript object, and you can trust your own PHP not to include injection code in there.
var justDates = [];
for (var i=0; i < unavailableDates1.length; i++) {
justDates.push(unavailableDates1[i]['RegDate']);
}
Each Object ({'RegDate:'date'}) is an item in a javascript array. To get an item you use a numerical index. so to get the first item would be theArray[0] this would give you {"RegDate":"31-03-2011"}. Then to get that particular date string you just have to use the key theArray[0]['RegDate']!. So since you want to go through every member of a list, you should get the list length using .length.
For loops are usually used for this type of iteration and not for..in. because for in can access properties that are undesired! http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/
have a look at how to iterate over an array.
You can do something like:
dates = new Array();
unavailableDates1.forEach(function (obj){
dates.push(obj.RegDate);
};
Try the following:
JavaScript:
var x = [{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"23-08-2011"},{"RegDate":"07-09-2011"},{"RegDate":"09-09-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"03-11-2011"},{"RegDate":"03-11-2011"},{"RegDate":"11-11-2011"},{"RegDate":"16-11-2011"},{"RegDate":"18-11-2011"},{"RegDate":"21-11-2011"},{"RegDate":"02-12-2011"},{"RegDate":"02-12-2011"},{"RegDate":"12-12-2011"}];
var ary = new Array();
for (foo in x) {
ary.push(x[foo].RegDate);
}
console.log(ary);
jsFiddle example.
I noticed you tag jquery in here as well so, here's a jquery solution:
http://jsfiddle.net/aztechy/DK9KM/
var foo = [
{"RegDate":"31-03-2011"},
{"RegDate":"29-07-2011"},
{"RegDate":"09-08-2011"},
{"RegDate":"09-08-2011"}
];
var datesArray = [];
$.each(foo, function() {
datesArray.push(this.RegDate);
});
console.log(datesArray);
Try This, it may works.
var unavailableDates = [];
for(var i = 0; i < unavailableDates1.length; i++){
unavailableDates[i] = unavailableDates1[i].RegDate;
}
for(var i=0;i<unavailableDates.length;i++) {
unavailableDates[i] = unavailableDates[i].RegDate;
}