You want to json_encode($json, JSON_FORCE_OBJECT).

The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.

You can also eliminate the use of array_push for some slightly cleaner code:

$json[] = ['ip' => $ip, 'port' => $port];
Answer from jbafford on Stack Overflow
๐ŸŒ
ProxyScrape
proxyscrape.com โ€บ tools โ€บ php-to-json
PHP Array to JSON Converter - ProxyScrape Tools
Free online tool to convert PHP arrays to JSON format. Convert PHP array syntax to valid JSON objects and arrays with proper formatting. Perfect for PHP developers working with APIs.
Discussions

How to convert this PHP array of objects to json? - Stack Overflow
I have an array of 10 objects that I am trying to convert to JSON. The array is being stored in a variable called $invoices. Below is the ouput of var_dump($invoices) shorted to only the first ob... More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 27, 2017
[HELP] json_decode on PHP fails to convert an array of JSON objects
can you C/P error. I don't know why are you using json_decode. Can you try without json_decode?. Sample::insert($samples); More on reddit.com
๐ŸŒ r/laravel
9
0
April 12, 2017
Opis JSON Schema: Is it possible to generate a schema from a PHP array or object?
Looking at the docs here , your example lacks "properties" => (object) [ and "myString" => (object) [. Note that casting an array to object isn't a recursive operation, so you need to manually cast everything withing the schema that need to be an object. Alternatives: Start with actual object: $schema = new stdClass; The validator accepts JSON encoded stings, so you can json_encode the array or use the Helper::toJSON() method. PS: I tried to achieve this and I keep getting several Fatal Errors in PHP It's very important to try to understand those error messages, as they likely point to the fix. Or at least include then in your post, so we know about them. When reading your post, I was unsure if the example provided was the one having errors. More on reddit.com
๐ŸŒ r/PHPhelp
3
2
February 21, 2024
How to loop this JSON object from php?
First of all, you have an error in your JSON data. Here is the fixed one: { "data": [ { "section": "Technology", "weighting": "0.15", "questions": [ { "id": "1", "weighting": "0.25", "score": "5" }, { "id": "2", "weighting": "0.25", "score": "5" } ] }, { "section": "Data", "weighting": "0.15", "questions": [ { "id": "1", "weighting": "0.25", "score": "5" }, { "id": "2", "weighting": "0.25", "score": "5" } ] } ] } I, then, created a file 'data.json' and 'test.php'. Here is 'test.php': '; } } It prints: 0.25 0.25 0.25 0.25 As you see, you made two mistakes: Your JSON data was corrupted and you were looping the whole array, but you have to loop array['data']. Hope it helps. P.S.: Get better in debugging PHP with print_r and echoes. Really helps. More on reddit.com
๐ŸŒ r/PHPhelp
11
7
August 23, 2020
People also ask

When would I need to convert PHP array to JSON?
Common use cases: creating API responses from PHP backend, saving data to localStorage from Ajax calls, passing data from PHP to JavaScript on the same page (use json_encode in PHP variable), storing structured data in database JSON columns, and creating configuration files in JSON format from PHP-based admin panels.
๐ŸŒ
tools.dotiam.com
tools.dotiam.com โ€บ home โ€บ php array to json
PHP Array to JSON Converter - Convert PHP to JSON Online | Free ...
What PHP array features cannot be converted to JSON?
PHP-specific features that don't map to JSON: PHP resources (file handles, database connections), objects with methods (JSON only stores properties), undefined values, integer-keyed associative arrays (JSON object keys must be strings), and circular references. Our converter handles simple data arrays โ€” complex object graphs may need manual review.
๐ŸŒ
tools.dotiam.com
tools.dotiam.com โ€บ home โ€บ php array to json
PHP Array to JSON Converter - Convert PHP to JSON Online | Free ...
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ php โ€บ 0kvtdskv โ€บ php-array-to-json-example
How do I convert PHP Array to JSON?
To convert a PHP array to JSON data string, you can use the json_encode($value, $flags, $depth) function. The json_encode() function takes a PHP array as input and returns a JSON string representation.
๐ŸŒ
DotIAM Tools
tools.dotiam.com โ€บ home โ€บ php array to json
PHP Array to JSON Converter - Convert PHP to JSON Online | Free Tool | DotIAM Tools
Free PHP Array to JSON converter. Transform PHP arrays, objects, and variables into clean JSON format instantly. Perfect for API development, data export, and Laravel/WordPress projects. Works with nested arrays.
๐ŸŒ
Scout APM
scoutapm.com โ€บ home โ€บ blog โ€บ php json_encode: serialize php objects to json
PHP Json_encode: Serialize PHP Objects to JSON | Scout Monitoring
May 1, 2020 - Let us look at what these are and some examples of how we can encode each of these into JSON - Indexed arrays are conventional arrays that are represented by index numbers. ... Associative arrays are arrays that use named keys as indices for your values. Example: $age = array("John"=>"11", "Ken"=>"19", "Tim"=>"14"); We can also arrive at the book JSON object that we saw above by encoding an Associative array as such - <?php $book = array("id"=>101, "label"=>"Lorem Ipsum"); echo json_encode($book); ?>
๐ŸŒ
Medium
inyomanjyotisa.medium.com โ€บ how-to-convert-a-php-array-to-json-c0bf63df5b33
How to Convert a PHP Array to JSON | by I Nyoman Jyotisa | Medium
October 18, 2024 - How to Convert a PHP Array to JSON Converting a PHP array to JSON is straightforward using the json_encode() function. Here's an example: $array = [ "foo" => "bar", "baz" => "qux", ]; $json โ€ฆ
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ how-to-convert-php-array-to-javascript-or-json
How to convert PHP array to JavaScript or JSON ? - GeeksforGeeks
July 12, 2025 - json_encode( $my_array ); Example 1: This example uses json_encode() function to convert PHP array to JavaScript JSON object.
๐ŸŒ
bishrulhaq
bishrulhaq.com โ€บ home โ€บ posts โ€บ convert php array to json : examples
Convert PHP Array To JSON : Examples | BH
July 1, 2026 - The syntax of json_encode() function as following. ... <?php $names = ['Bishrul', 'Bishrul Haq', 'Developer', 'Software Engineer']; $namesJSON = json_encode($names); echo "Names in JSON :".$namesJSON; ... <?php $names = ['Bishrul', 'Bishrul ...
๐ŸŒ
PHPpot
phppot.com โ€บ php โ€บ php-array-to-json
PHP Array to JSON String Convert with Online Demo - PHPpot
Creating an online tool to convert a PHP array to a JSON object and handling pre-post actions of the array to JSON conversion.
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.json-encode.php
PHP: json_encode - Manual
Returns a string containing the JSON representation of the supplied value. If the parameter is an array or object, it will be serialized recursively. If a value to be serialized is an object, then by default only publicly visible properties will be included.
Top answer
1 of 4
2

The best way is to implement JsonSerializable class and define the jsonSerialize() function

Example:

class MyObj implements JsonSerializable{
    protected $id;
    protected $name;

    function getId() { return $this->$id; }
    function getName() { return $this->$name; }
  
     public function jsonSerialize() {
                return [
                'Id' => $this->getId(),
                'Name' => $this->getName()
            ];
        }
}

// $arrofobj is array of objects of type MyObj 
json_encode($arrofobj);  //this will convert array of objects to JSON
2 of 4
1

If these classes cannot implement JsonSerializable you may access the protected properties using Reflection.

Example:

class Publisher {
    protected $name;
    protected $id;
    public function __construct($id, $name) {
        $this->id = $id;
        $this->name = $name;
    }
}

function getPublisherExportData($publishers) {
    $out = [];
    foreach($publishers as $publisher) {
        $currentPData = [];
        $refl = new ReflectionClass($publisher);
        $props = $refl->getProperties(ReflectionProperty::IS_PROTECTED);
        foreach($props as $prop) {
            $prop->setAccessible(true);
            $currentPData[$prop->getName()] = $prop->getValue($publisher);
        }
        $out[] = $currentPData;
    }

    return $out;
}

var_dump(json_encode(getPublisherExportData([new Publisher(12, 'My Name'), new Publisher(15, 'NameProperty')]), JSON_PRETTY_PRINT));

Will result in:

string(121) "[ { "name": "My Name", "id": 12 }, { "name": "NameProperty", "id": 15 } ]"

However, you will need to handle object graphs and conditional exports yourself. Depending on the required json output you might think about replacing $out with an instance of stdClass and write using the $out->{$prop->getName()} = $val syntax to it.

If you are able to use your custom implementations you could add a method using get_object_vars($this) to avoid most of the code above, however if you could do that you should consider implementing JsonSerializable which is meant for that task.

๐ŸŒ
Jonathan Suh
jonsuh.com โ€บ blog โ€บ convert-loop-through-json-php-javascript-arrays-objects
Convert and Loop through JSON with PHP and JavaScript Arrays/Objects โ€” Jonathan Suh
September 30, 2014 - Note the differences in accessing the values of an array vs an object. PHP also features a json_encode function to convert an array or object into a string.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ how-to-create-an-array-for-json-using-php
How to create an array for JSON using PHP? - GeeksforGeeks
July 11, 2025 - These keys will be a string or an integer which will be used as an index to search the corresponding value in the array. The json_encode() function is used to convert the value of the array into JSON. This function is added in from PHP5.
๐ŸŒ
AppDevTools
appdevtools.com โ€บ php-array-to-json-converter
PHP Array to JSON Converter - App DevTools
PHP Array to JSON is a tool that converts a PHP array to JSON data. Enter a PHP array in the input field and click the convert button.
๐ŸŒ
Coddy.Tech
coddy.tech โ€บ docs โ€บ php โ€บ json_encode()
PHP json_encode(): Convert Arrays and Objects to JSON
3 weeks ago - An associative array becomes a JSON object, a list (keys 0, 1, 2...) becomes a JSON array, and strings, numbers, true, false and null become their JSON equivalents. <?php $user = [ 'name' => 'Ada', 'age' => 36, 'langs' => ['php', 'js'], 'admin' => true, 'manager' => null, ]; $json = json_encode($user); echo $json, "\n"; echo gettype($json), "\n";
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ how-to-encode-array-in-json-php
How to Encode Array in JSON PHP ? - GeeksforGeeks
July 23, 2025 - PHP provides a built-in function json_encode() to encode PHP data structures, including arrays, into JSON format.
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ php โ€บ 0uwqq41y โ€บ json-to-array-php-example
How do I convert JSON to PHP array?
PHP provides many built-in functions for manipulating arrays, including sorting, searching, checking if an element exists in an array, splitting string to array, converting array to string, converting array to JSON, and getting the length of an array. JSON (JavaScript Object Notation) is a language-independent text format for storing and exchanging data.