This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to fetch array keys with jQuery?
php built-in function array_keys(), equivalent in jquery
is there any built in function in jquery similar to that of php array_keys(),.
please suggest
You will have to define your own function to get the same functionality. Try this:
function arrayKeys(input) {
var output = new Array();
var counter = 0;
for (i in input) {
output[counter++] = i;
}
return output;
}
arrayKeys({"one":1, "two":2, "three":3}); // returns ["one","two","three"]
No there isn't anything specific in jQuery for this. There is a javascript method but it is not widely supported yet Object.keys() so people don't use it for generic projects. Best thing i could think of is
var keys = $.map(your_object, function(value, key) {
return key;
});
You don't need jQuery or any other library for this -- it's a standard part of Javascript.
for(var key in myObject) {
alert(key);
}
That should be sufficient for you to loop through the object. But if you want to actually get the keys into their own array (ie turn it into a genuine clone of the php function), then it's fairly trivial to extend the above:
function array_keys(myObject) {
output = [];
for(var key in myObject) {
output.push(key);
}
return output;
}
Note, there are caveats with using the for(..in..) technique for objects that have properties or methods that you don't want to include (eg core system properties), but for a simple object that you've created yourself or from a JSON string, it's ideal.
(For more info on the caveats, see http://yuiblog.com/blog/2006/09/26/for-in-intrigue/)
Take a look at PHPJS, a project that aims to reproduce many PHP functions in vanilla JavaScript with minimal dependencies. In your case, you want array_keys.
In JavaScript there's no such thing like associative arrays. Objects (object literals) handle similar cases.
var keys = [], i = 0;
for( keys[ i++ ] in yourObject );
And now keys contains all yourObject property names (keys).
Related
How can I make a html table which the user can sort using the column headers to sort on the client side? I can load all rows' html data into a Javascript array and use dom to add a table to a content div but is it the right way? If you list major methods, I can find my way from there so, I'm not asking for code.
http://tinysort.sjeiti.com/ should be usefully
No need to reinvent the wheel in case you utilise a JS Framework already, but here are quite some nice solutions:
TableSort - http://www.frequency-decoder.com/demo/table-sort-revisited/
JQuery tablesorter - http://tablesorter.com/docs/#Demo
GridView3 - http://dev.sencha.com/playpen/ext-2.0/examples/grid/grid3.html
Stuart Langridge's Script - http://yoast.com/articles/sortable-table/
Mootools Mootable - http://joomlicious.com/mootable/
tablesorter is good, but you want something that has filtering built in, and is pretty widely used and supported try http://datatables.net/
Every tablesorter works like this:
get the table.tbody.rows in an array
sort that array using a custom compare function
append the rows to the table body in the correct order
It is usually be a bit faster if you precompute the values-to-compare (instead of accessing the DOM elements on every comparison), the array would then contain objects that have the value in one slot and the table row element in the other.
If you have an array, then calling sort() is probably your best bet:
function sortArray(a, b){
//could also say return a-b instead of the blown out if...else construct
if(a.Age===b.Age) { return 0; }
else if (a.Age < b.Age) { return -1; }
else { return 1; }
}
var rows = [{Name: 'Amy', Age: 10}, {Name: 'Bob', Age: 20}];
var sortedArray = rows.sort(sortArray);
As the other answers have stated, you can also use a plug-in. DataTables is a good one that I've used in the past.
I have an array of 500k values, and I need to convert it into one big json object, I could not find such a possibility in the helper. Another important point I do not want to twist the foreach, because it is not productive.
You could use Json class in yii2 from
yii\helpers\Json;
It contain methods such as :
Json::encode();
Json::decode();
These methods directly converts yii2 activerecord objects into json array.
I'm just wondering if the below line won't be sufficient ?
var myJsonString = JSON.stringify(yourArray);
You can use ES5 Array.reduce for this use case,if you are working on es5.
var array500Values=[0,1,2,3,4,5,6,7];
var json500 = array500Values.reduce(function(acc, val) {
acc[val]=val;
return acc;
}, {});
console.log(json500);
I am using PHP, MySQL, and javascript. I use php to connect to my database to select appointments. I then echo them in a script tag as arrays of object literals (JSON objects):
appointment[$apptid] = {"time":"8:00", "date":"2012-02-10", "description":"testAppt"};
...
I chose to do it this way over writing an appointment "class" in case I add or remove appointment fields, however I can't figure out for the life of me how to create functions that will apply to this array of objects. Is there anyway to declare these as appointment objects and then write prototype functions without losing the properties?
I'm not 100% sure that I understand what you're after, but if I understand then maybe this is what you want:
First of all, in javascript you better use arrays in a different way than in php, so do something like:
var appointments = [];
appointments.push({"time":"8:00", "date":"2012-02-10", "description":"testAppt"});
Now, once you the array you can do something like:
function doSomething() {
alert(this.time);
}
for (var i = 0; i < appointments.length; i++) {
appointments[i].doSomething = doSomething;
}
Check out JSON.parse: http://www.json.org/js.html
Using this, you can parse your JSON strings into appointment objects that contain your variables as defined in the JSON string, with no prototyped functions.
Then, if you want to get really fancy, you can use the "reviver" parameter to pass in a function in which you could define the functions for each appointment object.
Am trying to pass an array of values from PHP function to Javascript. Not sure if I am doing it correctly.
PHP:
function toggleLayers(){
for($i=0;$i<$group_layer_row;$i++){
$toggleArray=mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
return $toggleArray;
}
}
JS:
var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
for(var i=0;i < myArray.length; i++){
if($myArray.getVisibility()==true){
$myArray.getVisibility(false);
}
else{
$myArray.getVisibility(true);
}
}
SQL (for reference):
$con = mssql_connect("myServer", "myUsername", myPassword");
$sql = "SELECT * FROM m_group_layer WHERE group_id=\"".$_SESSION["group_id"]."\" ORDER BY display_order";
$rs_group_layer = mssql_query ($sql, $con);
$group_layer_row = mssql_num_rows($rs_group_layer);
I have been looking at some other similar questions, and the answers are either vague and/or there are a few thousand of them.
Would appreciate any help, also please try to explain as if you were writing a book called "Idiot's Guide to Passing PHP Arrays to JS"
Thanks for your help.
Edit:
Sorry, my question was very vague. Here's what I'm trying to do:
1.PHP Function gets all records from table into array(in this case they are map layers)
2.Javascript receives PHP array and loops through adding if clause to toggle layers.
Hope this makes it clearer.
It's simpler than you think.
Change this line:
var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
To just:
var myArray = <?php echo htmlspecialchars(json_encode($toggleArray), ENT_NOQUOTES); ?>;
json_encode produces a json string. Echoing the string into a javascript context is the equivalent of a javascript literal. The htmlspecialchars is just for the necessary html escaping and is not unique to echoing json.
NOTE however that you can only json_encode a php object or array, not any scalar types like ints or strings. This is a limitation of JSON itself. In your toggleLayers() function, you are returning a string, not an array.
A thing that would be very useful to understand:
You sumply can't "pass an array of values from PHP function to Javascript".
But rather you have to create the javascript code using PHP just like you are creating HTML.
Thus, 3 simple step to solve any problem with PHP -> client transfers:
Create a pure client-side code you wish. Make it work. Save it somewhere.
Create a PHP code to produce that client-side code.
Compare the codes. If doesn't match - correct the PHP code. Repeat until done.
I create this output with PHP:
foreach ($bk as $blink) {
$out["url"][] = $blink->url;
$out["anchor"][] = $blink->anchor;
}
$json = Zend_Json::encode($out);
echo ($json);
I want to receive and process the output with a $.ajax call.
Could you point me to a nice tutorial about multidimensional arrays with javascript/jquery or help me loop* through the json results? I got a bit confused with it.
I am trying to put those on a table, so I will be using <td>url-i</td><td>anchor-i</td> . This part, I figured out how. To put the correct values on url-i and anchor-i is the problem.
I would imagine the JSON output for that will be something like:
{'url': ['url1', 'url2', ... ],
'anchor': ['anchor1', 'anchor2', ... ]}
If that is the case, then they will be of equal length (and importantly equal indexes) and you can loop through one of the two using jQuery.each().
$.getJSON('jsonapp.php', function(data) {
$.each(data.url, function(index, url) {
var anchor = data.anchor[index];
$('#mytable').append('<tr><td>' + url + '</td><td>' + anchor +'</td></tr>');
});
});
I've not run that code, so it might have a few flaws, but that's the gist of it.
PHP can try to cast objects into arrays by itself, and for simple stuff, it usually works fine.
As for multidimensional arrays, Javascript isn't too different from most other higher-level programming/scripting languages when it comes to arrays. Really, any tutorial online on multidimensional arrays will do just fine. A multidimensional array is simply an array of arrays.
When you receive the string client-side, you just want to parse it. jQuery has its own method, but you can use JSON.parse. Afterwards, based on how you've set up your arrays, you'd want to do something like this.
<? $count = count($json_parsed['url']); for($i = 1; $i < $count; $i++) : ?>
<td><?=$json_parsed['url'][$i];?></td>
<td><?=$json_parsed['anchor'][$i];?></td>
<? endfor; ?>
This may be philosophically not the best way to do it though. If you have a whole bunch of objects and you want to make a table out of them, the best way would be to create an array of those objects as represented by associative arrays (sort of like hash tables in other programming languages). PHP natively tries to convert objects into associative arrays. I wouldn't be surprised if Zend_Json::encode does it automatically. If it does, you might want to pull simply:
echo Zend_Json::encode($bk);
If not, let me know, and we'll talk about how to do that.
You could have a look on any template frameworks, but for this exact case it seams useful to check one of those two: pure by beebole or jquery pure html templates.
Doing it by yourself might be tempting but why to reinvent the well - I know from my experience, that frameworks are about 2 times faster, then self made code.