Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSON object using PHP [duplicate]

Tags:

How can I achieve or create this type JSON object using PHP?

{      "label": "Devices per year",     "data": [         [1999, 3.0], [2000, 3.9], [2001, 2.0], [2002, 1.2], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]     ] } 

After several attempt I didn't find the solution. For example I tried this:

$arrayDateAndMachine = array(     "1999"=>3.0,      "2000"=>3.9 );     $arr = array(     "label" => "Devices per year",      "data" => $arrayDateAndMachine );  var_dump(json_encode($arr)); 
like image 654
d_raja_23 Avatar asked Dec 04 '13 17:12

d_raja_23


People also ask

How to create a JSON object from a PHP array?

The best way to create a JSON object is to start from a PHP array. The reason is that PHP arrays are a perfect match for the JSON structure: each PHP array key => value pair becomes a key => value pair inside the JSON object. The $json variable looks like this: The variable to be encoded as a JSON object. ( $array, in the previous example).

How to convert a request to JSON in PHP?

PHP File explained: 1 Convert the request into an object, using the PHP function json_decode (). 2 Access the database, and fill an array with the requested data. 3 Add the array to an object, and return the object as JSON using the json_encode () function. More ...

What is the best way to create a JSON object?

The best way to create a JSON object is to start from a PHP array. The reason is that PHP arrays are a perfect match for the JSON structure: each PHP array key => value pair becomes a key => value pair inside the JSON object. The $json variable looks like this: json_encode () takes three arguments:

What is @JSON_decode () in PHP?

json_decode (), as its name suggests, decodes a JSON string into a PHP object or array. All the variables contained in the JSON object will be available in the PHP object or array. Here is how it works. Let’s take our first JSON object example:


1 Answers

$obj = new stdClass(); $obj->label="Devices per year"; $obj->data = array(     array('1999','3.0'),     array('2000','3.9'),     //and so on... );  echo json_encode($obj); 
like image 71
V G Avatar answered Sep 17 '22 23:09

V G