I've encoded an Array I've made using the inbuilt json_encode();
function. I need it in the format of an Array of Arrays like so:
[["Afghanistan",32,12],["Albania",32,12]]
However, it is returning as:
["2":["Afghanistan",32,12],"4":["Albania",32,12]]
How can I remove these row numbers without using any Regex trickery?
A common use of JSON is to read data from a web server, and display the data in a web page.
This chapter will teach you how to exchange JSON data between the client and a PHP server.
PHP has some built-in functions to handle JSON.
Objects in PHP can be converted into JSON by using the PHP function json_encode():
<?php_x000D_
$myObj->name = "John";_x000D_
$myObj->age = 30;_x000D_
$myObj->city = "New York";_x000D_
_x000D_
$myJSON = json_encode($myObj);_x000D_
_x000D_
echo $myJSON;_x000D_
?>
_x000D_
If you don't specify indexes on your initial array, you get the regular numric ones. Arrays must have some form of unique index
I want to add to Michael Berkowski's answer that this can also happen if the array's order is reversed, in which case it's a bit trickier to observe the issue, because in the json object, the order will be ordered ascending.
For example:
[
3 => 'a',
2 => 'b',
1 => 'c',
0 => 'd'
]
Will return:
{
0: 'd',
1: 'c',
2: 'b',
3: 'a'
}
So the solution in this case, is to use array_reverse
before encoding it to json
I had a problem with accented characters when converting a PHP array to JSON. I put UTF-8 stuff all over the place but nothing solved my problem until I added this piece of code in my PHP while loop where I was pushing the array:
$es_words[] = array(utf8_encode("$word"),"$alpha","$audio");
It was only the '$word' variable that was giving a problem. Afterwards it did a jason_encode no problem.
Hope that helps
json_encode() function will help you to encode array to JSON in php.
if you will use just json_encode function directly without any specific option, it will return an array. Like mention above question
$array = array(
2 => array("Afghanistan",32,13),
4 => array("Albania",32,12)
);
$out = array_values($array);
json_encode($out);
// [["Afghanistan",32,13],["Albania",32,12]]
Since you are trying to convert Array to JSON, Then I would suggest to use JSON_FORCE_OBJECT as additional option(parameters) in json_encode, Like below
<?php
$array=['apple','orange','banana','strawberry'];
echo json_encode($array, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
Source: Stackoverflow.com