[php] How to create an array for JSON using PHP?

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?

This question is related to php json

The answer is


<?php 

    $username=urldecode($_POST['log_user']);

    $user="select * from tbl_registration where member_id= '".$username."' ";
    $rsuser = $obj->select($user);
    if(count($rsuser)>0)
    {
        //   (Status if 2 then its expire)    (1= use) ( 0 = not use)

        $cheknew="select name,ldate,offer_photo  from tbl_offer where status=1 ";
        $rscheknew = $obj->selectjson($cheknew);

        if(count($rscheknew)>0)
        {

             $nik=json_encode($rscheknew);
            echo "{\"status\" : \"200\" ,\"responce\" : \"201\", \"message\" : \"Get Record\",\"feed\":".str_replace("<p>","",$nik). "}";
        }
        else
        {
            $row2="No Record Found";
            $nik1=json_encode($row2);
            echo "{\"status\" : \"202\",  \"responce\" : \"604\",\"message\" : \"No Record Found \",\"feed\":".str_replace("<p>","",$nik1). "}";
        }
    }
    else
    {
        $row2="Invlid User";
        $nik1=json_encode($row2);
        echo "{\"status\" : \"404\", \"responce\" : \"602\",\"message\" : \"Invlid User \",\"feed\":".str_replace("<p>","",$nik1). "}";
    }

 ?>

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).


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();
    }

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)

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.


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);

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);

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);

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"}]

$json_data = '{ "Languages:" : [ "English", "Spanish" ] }';
$lang_data = json_decode($json_data);
var_dump($lang_data);