146

From PHP code I want to create an json array:

[
  {"region":"valore","price":"valore2"},
  {"region":"valore","price":"valore2"},
  {"region":"valore","price":"valore2"}
]

How can I do this?

2

8 Answers 8

172

Easy peasy lemon squeezy: http://www.php.net/manual/en/function.json-encode.php

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

There's a post by andyrusterholz at g-m-a-i-l dot c-o-m on the aforementioned page that can also handle complex nested arrays (if that's your thing).

0
137

Use PHP's native json_encode, like this:

<?php
$arr = array(
    array(
        "region" => "valore",
        "price" => "valore2"
    ),
    array(
        "region" => "valore",
        "price" => "valore2"
    ),
    array(
        "region" => "valore",
        "price" => "valore2"
    )
);

echo json_encode($arr);
?>

Update: To answer your question in the comment. You do it like this:

$named_array = array(
    "nome_array" => array(
        array(
            "foo" => "bar"
        ),
        array(
            "foo" => "baz"
        )
    )
);
echo json_encode($named_array);
1
  • 2
    Excuse me but if I want {"nome_array": [{"foo":"bar"},{"foo":"baz"}]} ??
    – Mimmo
    Jul 18, 2011 at 23:12
49

Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:

$a = array(
        array('foo' => 'bar'),
        array('foo' => 'baz'));
$json = json_encode($a);

Gives you:

[{"foo":"bar"},{"foo":"baz"}]
3
  • 1
    Excuse me but if I want {"nome_array": [{"foo":"bar"},{"foo":"baz"}]} ??
    – Mimmo
    Jul 18, 2011 at 22:45
  • 3
    Read my post again. If you want something to translate into a JSON object, make it an associative array in PHP (where the keys are strings). If you want it to translate into a JSON list, make it a plain array (with implicit integer keys). The value of each array element can in turn be an array, which is what you want.
    – tdammers
    Jul 19, 2011 at 8:56
  • Also, array indices need to start on 0. If they are 1-based, they get converted to k-v objects.
    – sivann
    Feb 3, 2022 at 12:40
16

Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.

After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc function, which also return one associative array.

$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';

... etc.

After that.

json_encode($associativeArray);
9

also for array you can use short annotattion:

$arr = [
    [
        "region" => "valore",
        "price" => "valore2"
    ],
    [
        "region" => "valore",
        "price" => "valore2"
    ],
    [
        "region" => "valore",
        "price" => "valore2"
    ]
];

echo json_encode($arr);
1
  • Shame I had to scroll so far for this..
    – Prid
    Dec 25, 2023 at 5:06
4

That's how I am able to do with the help of solution given by @tdammers below. The following line will be placed inside foreach loop.

$array[] = array('power' => trim("Some value"), 'time' => "time here" );

And then encode the array with json encode function

json_encode(array('newvalue'=> $array), 200)
2

Just typing this single line would give you a json array ,

echo json_encode($array);

Normally you use json_encode to read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.

1

I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.

<?php

// define a JSON Object class
class jsonOBJ {
    private $_arr;
    private $_arrName;

    function __construct($arrName){
        $this->_arrName = $arrName;
        $this->_arr[$this->_arrName] = array();

    }

    function toArray(){return $this->_arr;}
    function toString(){return json_encode($this->_arr);}

    function push($newObjectElement){
        $this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
    }

    function add($key,$val){
        $this->_arr[$this->_arrName][] = array($key=>$val);
    }
}

// create an instance of the object
$jsonObj = new jsonOBJ("locations");

// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));

$jsonObj->add("location","TestLoc3"); // from key:val pairs

echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>

Will output:

Array
(
    [locations] => Array
        (
            [0] => Array
                (
                    [location] => TestLoc1
                )

            [1] => Array
                (
                    [location] => TestLoc2
                )

            [2] => Array
                (
                    [location] => TestLoc3
                )

        )

)


{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}

To iterate, convert to a normal object:

$myObj = $jsonObj->toArray();

Then:

foreach($myObj["locations"] as $locationObj){
    echo $locationObj["location"] ."<br />";
}

Outputs:

TestLoc1
TestLoc2
TestLoc3

Access direct:

$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];

A practical example:

// return a JSON Object (jsonOBJ) from the rows
    function ParseRowsAsJSONObject($arrName, $rowRS){
        $jsonArr = new jsonOBJ($arrName); // name of the json array

        $rows = mysqli_num_rows($rowRS);
        if($rows > 0){
            while($rows > 0){
                $rd = mysqli_fetch_assoc($rowRS);
                $jsonArr->push($rd);
                $rows--;
            }
            mysqli_free_result($rowRS);
        }
        return $jsonArr->toArray();
    }

Not the answer you're looking for? Browse other questions tagged or ask your own question.