Convert array to json without cycle - php

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

Related

Iterate only through objects

I am receiving some JSON from PHP like this (previewed in Firefox tools):
1:Object
0:Object
1:Object
2:Object
3:Object
Name: "SomeName"
I now want to iterate through the objects, but not the Name key. It seems if I do an $.each it includes the key/value pair. How can I avoid it? Also why can I choose a numerical value for the first Object (I have it "1") but not assign a value to it? I wish it could look like this for example
1:SomeNameIGaveIt
0:Object
1:Object
2:Object
3:Object
That would make my Name k/v pair obsolete.
JSON
{"1": {"Name":"SomeName", "0":{"data":"data"}. "1":{"data":"data"}}}
In JavaScript, a String is a "subclass" of Object. Lucky for you, there's the typeof operator;
in the Chrome console
var a = "foo" //makes a String
var b = {} //makes an empty Object
typeof a
"string"
typeof b
"object"
Using this, you can check to ensure something is not a string before doing an operation on it.
Other option: instead of iterating using the json $.each call, you could just iterate over it via a JavaScript for-loop. If you know the number of elements inside your SomeNameIGaveIt object is fixed, you could use a fixed number of iterations and then use the array indexing operator (SomeNameIGaveIt[index]), or use a for-in loop (for (var i in array){...})
If you use a for-in loop, you can check if the index is a number using typeof as mentioned above. Any of these approaches is going to yield pretty similar results, so pick whatever suits you best.

Split an array within an array (Mysql, PHP and Ajax)

I have a database with 5 columns and multiple rows. I'm using PHP to fetch the data and echo it as JSON as an array. The way it echoes it is the data in each row is an array and the rows themselves are an array (array within an array).
Now I bring the data in using Ajax and want to split the array within an array. I can only split down the rows so far. How would I split further?
Here's the PHP:
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
//==== PUT DATA INTO ARRAY
$array = array();
while ($row = mysql_fetch_row($result)) {
$array[] = $row;
}
//==== ECHO AS JSON
echo json_encode($array);
Here's the Ajax:
$.ajax({
url: 'assets/php/results.php',
data: "",
dataType: 'json',
success: function(data){
//==== FETCH DATA FIELDS
var row1 = data[0];
var row2 = data[1];
//==== UPDATE HTML WITH DATA
$('#r-col span.row1').html(row1);
$('#r-col span.row2').html(row2);
}
});
To answer your question, let me give you a few tips on how you can achieve this in shorter steps.
First off, try using msqli_ functions instead of msql_ (in php) it has a better handling of security among other improvements, and are also the functions w3schools recommend using.
There is a function called mysqli_fetch_array() that will do exactly what you are doing with your for loop in a single command.
And to answer your question on the json, you should take a look at what a json really looks like:
var data = {"menu": {
"id": "file",
"value": "File123",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
Json objects are not arrays, they are objects. That means I can access the information like this:
data.menu.id //Which is equal to "file"<br>
or
data[0][0] //which is also equal to "file"<br>
or a combination
data[0].value //is equal to "File123"
A great way to understand the way this objects work is by using the interactive console in Chrome. It has a pretty easy to understand printing of objects. I would also advice you to read some about object oriented programming on javascript.
In a nutshell: Json objects are not arrays, but you can sort through them easily by appending . or []
A small note: Try to avoid using Select * in your statements, they take a lot of resources, just call the fields you need by name.
Also, msql_ functions are a bit deprecated right now, try using msqli_ functions instead, they have several upgrades in the security side, you can check w3schools.com for examples.
Finally, there is a function in php called msqli_fetch_array that does exactly what you're trying to do with your for loop, it will convert your query output to an array.
Happy Coding.

php function array_keys equivalent in jquery [duplicate]

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

using prototype functions for an array of object literals

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.

jQuery json_encode

I've looked around for a Javascript/jQuery function which emulates PHP's json_encode, but all the ones I find (listed bellow) don't work.
http://code.google.com/p/jquery-json/
http://phpjs.org/functions/json_encode:457
To check if it wasn't my array wasn't faulty I used phpjs var_dump with expected results.
Can anyone point me in the right direction?
The problem is that you cannot do this:
ret[$(this).attr("id")] = _recursiveItems(this);
because var ret = [] declares ret as an Array and not an Object and $(this).attr("id") is non-numeric (its value is head_1). It is attempting to create an associative array which is not supported.. JavaScript associative arrays are are meant to be numeric and even considered harmful.
If you change the declaration to var ret = {} then you can use jquery-json to convert the object to JSON. Here is a demo using the code in the question.

Categories