I my php file, I need to make my own Json array.
for($i=1;$i<$arraySize+1;$i++){
$idJson[$i]=$i.":".$birdIDArray[$i-1];
}
for($i=$arraySize+1 ;$i<$arraySize*2+1; $i++){
$idJson[$i]=$i.":".$rankArray[$i-($arraySize+1)];
}
When I use
print(json_encode($idJson));
the OUTPUT : ["0:3","1:15","2:3","3:14","4:1","5:2","6:2"]
But i need the output like this ["0":"3","1":"15","2":"3","3":"14","4":"1","5":2","6":"2"]
When I going to add " mark
for($i=1;$i<$arraySize+1;$i++){
$idJson[$i]=$i.'"'.":".'"'.$birdIDArray[$i-1];
}
for($i=$arraySize+1 ;$i<$arraySize*2+1; $i++){
$idJson[$i]=$i.'"'.":".'"'.$rankArray[$i-($arraySize+1)];
}
It prints like this
["0:3","1\":\"15","2\":\"3","3\":\"14","4\":\"1","5\":\"2","6\":\"2"]
How can I avoid from printing this \ sign?
I'm assuming you want a JSON object like this:
{"0":"3", ... }
The problem here is that Javascript/JSON distinguishes between key-value pairs, which are objects, and numerically indexed lists, which are arrays, while PHP uses arrays for both these things. With json_encode it depends on whether the PHP array is a continuously numerically indexed array, in which case you get a JSON array, or anything else, in which case you get a JSON object.
What you want is to force a JSON object even for a continuously numerically indexed array. The first question here would be: why?! But if you're really sure you want that (again, why?!), there's the JSON_FORCE_OBJECT flag in PHP 5.3+:
echo json_encode(array("3", "15", "3"), JSON_FORCE_OBJECT);
// {"0":"3","1":"15","2":"3"}
But I'll say again that that's pretty pointless. If you use a regular array like ["3","15","3"], the keys to those elements are already implicitly 0, 1 and 2. There's no need to enforce them as object keys.
Related
I have an app which i'm making a HTTP request via PHP to retrieve some XML data. I'm then taking a string in that data, splitting it by spaces (" ") and pushing it into a new array. I'm then taking an existing array and de-duping it against this new array using the function array_diff. Here is my code below:
// THIS ARRAY IS MUCH LONGER BUT HAVE JUST PUT IN A FEW WORDS
$stopwords = array("a", "about", "above", "above", "across", "after", "afterwards", "again");
// this is my XML call
$test = simplexml_load_file('https://some-xml-endpoint.com/endpoint');
// defining a blank array where I want the result to go
$mappedWordsObj = [];
for($i = 0;$i < count($test->data);$i++) {
// if I echo this it returns me a string with no quotes (sometimes the quotes would be in there and I thought this may have been the issue)
$comment = chop(strtolower($test->data[$i]->comments));
// here I split the comment into an array by spaces
$wordsArray = explode(' ', $comment);
//here I compare my new array of words with the stopwords I want removed from the wordsArray
$arr_1 = array_diff($wordsArray, $stopwords);
// here I push into the $mappedWordsObj array
array_push($mappedWordsObj, $arr_1);
}
// here I push to the DOM the result to see how my array looks
echo json_encode($mappedWordsObj);
My issue is that in the resulting $mappedWordsObj array, I expect all the array items to be arrays themselves that contain the words but some of the items are getting inserted in the $mappedWordsObj as arrays with the words and others as objects with properties whos values are the words. Here is a snippet of the data returned:
{"0":"i","1":"just","2":"want","4":"switch","6":"existing","7":"t-mobile","8":"pay","13":"ee","14":"pay","15":"monthly.","16":"i","17":"don't","18":"want","20":"new","21":"phone!","23":"page","24":"does","26":"tell","31":"this!"},{"0":"just","2":"option","4":"'sim","5":"only'","9":"'radio","10":"button'","11":"forced","12":"selection."},
["voice","recignition"],
["testing","ol"],
{"0":"can't","1":"think","4":"i","7":"simple","9":"easy"},{"2":"instead","3":"lol"},
["n\/a"],
["great","website"],
I'd like to just have an array of arrays so can anyone please tell me where i've gone wrong?
Cheers
When you use json_encode, it will convert PHP arrays to either JSON arrays or JSON objects. Which one is output depends completely on the array keys in the PHP array. For PHP arrays with sequential, numeric indexes starting at 0, the JSON output will be an array. For PHP arrays with any other indexes, the JSON output will be an object.
The array_diff produces an array where the indexes are not sequential in some cases. You can use array_values to reindex the result before appending it to your output array.
array_push($mappedWordsObj, array_values($arr_1));
Side note - array_push actually isn't necessary here. You can use
$mappedWordsObj[] = array_values($arr_1);
The array_push documentation actually recommends doing it this way when you're only appending one item to the array. But, it's a pretty small optimization, so if array_push looks better to you, never mind. :)
I was trying to get some values from MySQL database and when converting into JSON array using json_encode() I got a JSON object , after a while I found out that the indices was the root cause of the problem
here's the example I mentioned
<?php
$array = array(0=>"zero",2=>"two");
$another_array=array(0=>"zero",1=>"one");
print_r(json_encode($array)); // output: {"0":"zero","2":"two"}
print_r(json_encode($another_array)); //output: ["zero","one"]
?>
so what's the reason for that ?
Because array(0=>"zero",1=>"one") is the same as array("zero", "one") and the JSON encoder assumes the latter is a list (since that's how PHP does lists) and has no way to tell the former from the latter.
If you want to force json_encode to treat all arrays as objects, pass JSON_FORCE_OBJECT as the second argument:
json_encode(array(0=>"zero",1=>"one"), JSON_FORCE_OBJECT)
// {"0":"zero","1":"one"}
If you always want a json list instead, get rid of the keys (e.g. using array_values()) before encoding.
So im trying to figure out the best way to get MySql table data into either a multidimensional PHP array or convert that multidimensional array into a json string.
Essentially what im trying to do is have a php include that returns the JSON string so i can iterate through it. I am needing a single key with multiple values, so im not 100% sure that im headed in the right direction.
I want to assign multiple values to the same key, for example:
[{"key1": "package1", "package2", "package3"}, {"key2": "package1", "package2", "package3", "package4"}]
I think that is not going to work right? Because i dont have any type of index's?
That is not valid JSON. The structure you are looking for would be something like:
[
{"key1": ["package1", "package2", "package3"]},
{"key2": ["package1", "package2", "package3", "package4"}]
^ An array as the value to the key "key1", "key2", etc..
]
At the PHP side, you would need something like:
For every row fetched from MySQL
$arr[$key] = <new array>
for each package:
append package to $arr[$key]
echo out json_encode($arr)
JS arrays have an implicit array keying, starting at index 0. What you've got is a perfectly valid JS array, the equivalent of having written:
var x = []; // create new empty array
x[0] = {"key1": .... }; // first object
x[1] = {"key2": ....} // second object
Note that the contents of your {} sub-objects is NOT valid.
You should never EVER built a JSON string by hand. It's too unreliable and easy to mess up. It's just easier to use a native data structure (php arrays/objects), then json_encode() them. Ditto on the other end of the process - don't decode the string manually. Convert to a native data structure (e.g. json_decode(), JSON.parse()) and then deal with the native structure directly.
essentially, JSON is a transmission format, not a manipulation format.
When doing a json_encode a multidimensional array in PHP, I'm noticing a different output simply by naming one of the arrays, as opposed to not naming them. For Example:
$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));
json_encode($arrytest)
gives a single array of multiple json objects
[{"a":1,"b":2},{"c":3},{"d":4}];
whereas simply assigning a name to the middle array
$arrytest = array(array('a'=>1, 'b'=>2),"secondarray"=>array('c'=>3),array('d'=>4));
json_encode($arrytest)
creates a single json object with multiple json objects inside
{"0":{"a":1,"b":2},"secondarray":{"c":3},"1":{"d":4}};
why would the 1st option not return the same reasults as the 2nd execpt with "1" in place of "secondarray"
In JSON, arrays [] only every have numeric keys, whereas objects {} have string properties. The inclusion of a array key in your second example forces the entire outer structure to be an object by necessity. The inner objects of both examples are made as objects because of the inclusion of string keys a,b,c,d.
If you were to use the JSON_FORCE_OBJECT option on the first example, you should get back a similar structure to the second, with the outer structure an object rather than an array. Without specifying that you want it as an object, the absence of string keys in the outer array causes PHP to assume it is to be encoded as the equivalent array structure in JSON.
$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));
// Force the outer structure into an object rather than array
echo json_encode($arrytest , JSON_FORCE_OBJECT);
// {"0":{"a":1,"b":2},"1":{"c":3},"2":{"d":4}}
Arrays with continuous numerical keys are encoded as JSON arrays. That's just how it is. Why? Because it makes sense.
Since the keys can be expressed implicitly through the array encoding, there is no reason to explicitly encoded them as object keys.
See all the examples in the json_encode documentation.
At the first option you only have numeric indexes (0, 1 and 2). Although they are not explicitly declared, php automatically creates them.
At the second option, you declare one of the indexes as an string and this makes PHP internally transform all indexes to string.
When you json encode the first array, it's not necessary to show the integers in the generated json string because any decoder should be able to "guess" that they are 0, 1 and 2.
But in the second array, this is necessary, as the decoder must know the key value in your array.
It's pretty simple. No indexes declared in array? Them they are 0, 1, 2, 3 and so on.
output of this as in json form is year1{a,b},year2{c}, year3{d}
**a has value 1 ,b=2,c=3,d=4 stored in array of year1's a,b years2's c and years3's d respectivily
$array1 = array('a'=>1, 'b'=>2);
$array2 = array('c'=>3);
$array3 = array('d'=>4)
$form = array("year1" =>$array1,
"year2" =>$array2,
"year3" =>$array3,
);
$data = json_encode($form);
i have an simple array:
array
0 => string 'Kum' (length=3)
1 => string 'Kumpel' (length=6)
when I encode the array using json_encode(), i get following:
["Kum","Kumpel"]
My question is, what is the reason to get ["Kum","Kumpel"] instead of { "0" : "Kum", "1" : "Kumpel" }?
"{}" brackets specify an object and "[]" are used for arrays according to JSON specification. Arrays don't have enumeration, if you look at it from memory allocation perspective. It's just data followed by more data, objects from other hand have properties with names and the data is assigned to the properties, therefore to encode such object you must also pass the correct property names. But for array you don't need to specify the indexes, because they always will be 0..n, where n is the length of the array - 1, the only thing that matters is the order of data.
$array = array("a","b","c");
json_encode($array); // ["a","b","c"]
json_encode($array, JSON_FORCE_OBJECT); // {"0":"a", "1":"b","2":"c"}
The reason why JSON_FORCE_OBJECT foces it to use "0,1,2" is because to assign data to obeject you must assign it to a property, since no property names are given by developer (only the data) the encoder uses array indexes as property names, because those are the only names which would make sense.
Note: according to PHP manual the options parameters are only available from PHP 5.3.
For older PHP versions refer to chelmertz's answer for a way to make json_encode to use indexes.
As Gumbo said, on the JS-side it won't matter. To force PHP into it, try this:
$a = new stdClass();
$a->{0} = "Kum";
$a->{1} = "Kumpel";
echo json_encode($a);
Not that usable, I'd stick with the array notation.
Just cast as an object and it will work fine...the JSON_FORCE_OBJECT parameter does exactly the same thing.
json_encode((object)$array);
Don't forget to convert it back into a php array so you can access its values in php:
$array = (object)$array;
$array = (array)$array;
json_encode($array);
Since you’re having a PHP array with just numeric keys, there is no need to use a JavaScript object. But if you need one, try Maiku Mori’s suggestion.
I personally think this is a bug that needs to be fixed in PHP. JSON_FORCE_OBJECT is absolutely not an answer. If you try to do any sort of generic programming you get tripped up constantly. For example, the following is valid PHP:
array("0" => array(0,1,2,3), "1" => array(4,5,6,7));
And should be converted to
{"0": [0,1,2,3], "1": [4,5,6,7]}
Yet PHP expects me to either accept
[[0,1,2,3],[4,5,6,7]]
or
{"0":{"0":1,"1":1,"2":2,"3":3},"1":{"0":4,"1":5,"2":6,"3":7}}
Neither of which are right at all. How can I possibly decode an object like that? What possible reason is there to ever change something that is clearly using strings as indexes? It's like PHP was trying to be clever to help out idiotic people who can't differentiate strings from ints, but in the process messed up anyone legitimately using strings as indexes, regardless of what the value COULD be turned into.