[php] PHP Array to JSON Array using json_encode();

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?

This question is related to php arrays json

The answer is


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():

_x000D_
_x000D_
<?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_
_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"} 
?>

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?