How to add json_encode array into json_encode object ? or other way to make below result?
php result response to jquery ajax
{”a_obj”:”a_obj”,“b_obj_json”:[
{“b_arr1”:b_arr1,“b_arr1-2”:“b_arr1-2”},
{“b_arr2”:b_arr2,“b_arr2-2”:”b_arr2-2”},
... from db push
]
}
:
$response_array = array('a_array'=>'a_array');
$response_array_object = json_encode($response_array, JSON_FORCE_OBJECT);
$b_arr =array(
'b_arr1'=>'b_arr1',
);
json_encode($b_arr);
$response_array_object->append($b_arr);
echo $response_array_object;
Convert JSON to Array with 'json_decode' then use 'array_append' to add new data then 'json_encode' it again.
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$array = (array) json_decode($json);
$append = array(
'username' => array('alias' => 'somename', 'realname' => 'stacky');
'password' => 'somepass';
);
$combined = array_merge($array, $append);
$encoded = json_encode($combined);
print_r($encoded);
?>
Related
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?
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).
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);
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"}]
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);
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);
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.
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();
}
I have this form of json :{"1":"7.00","2":"8.00"}
How can i transform it in this type of json?
{{"id":"1","qty":"7.00"},{"id":"2","qty":"8.00"}}
Thank you!
First is to json_decode() your JSON.
Now, you have an array with keys as IDs and values as quantities.
Iterate over the array and insert into the result with id and qty as keys.
Snippet:
<?php
$str = '{"1":"7.00","2":"8.00"}';
$data = json_decode($str,true);
$result = [];
foreach($data as $key => $val){
$result[] = [
'id' => $key,
'qty' => $val
];
}
echo json_encode($result);
Demo: https://3v4l.org/8VS4t
I need to convert a PHP array to JSON but I don't get what I expect.
I want it to be an object that I can navigate easily with a numeric index.
Here's an example code:
$json = array();
$ip = "192.168.0.1";
$port = "2016";
array_push($json, ["ip" => $ip, "port" => $port]);
$json = json_encode($json, JSON_PRETTY_PRINT);
// ----- json_decode($json)["ip"] should be "192.168.0.1" ----
echo $json;
This is what I get
[
[
"ip" => "192.168.0.1",
"port" => "2016"
]
]
But I want to get an object instead of array:
{
"0": {
"ip": "192.168.0.1",
"port": "2016"
}
}
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];
just use only
$response=array();
$response["0"]=array("ip" => "192.168.0.1",
"port" => "2016");
$json=json_encode($response,JSON_FORCE_OBJECT);
Just in case if you want to access your objectivitized json whole data OR a specific key value:
PHP SIDE
$json = json_encode($yourdata, JSON_FORCE_OBJECT);
JS SIDE
var json = <?=$json?>;
console.log(json); // {ip:"192.168.0.1", port:"2016"}
console.log(json['ip']); // 192.168.0.1
console.log(json['port']); // 2016
To get array with objects you can create stdClass() instead of array for inner items like below;
<?PHP
$json = array();
$itemObject = new stdClass();
$itemObject->ip = "192.168.0.1";
$itemObject->port = 2016;
array_push($json, $itemObject);
$json = json_encode($json, JSON_PRETTY_PRINT);
echo $json;
?>
A working example http://ideone.com/1QUOm6
In order to get an object and not just a json string try:
$json = json_decode(json_encode($yourArray));
If you want to jsonise the nested arrays as well do:
$json =json_decode(json_encode($yourArray, JSON_FORCE_OBJECT));
$ip = "192.168.0.1";
$port = "2016";
$json = array("response" => array("ip" => $ip, "port" => $port));
//IF U NEED AS JSON OBJECT
$json = [array("ip" => $ip, "port" => $port)]; //IF U NEED AS JSON ARRAY
$json = json_encode($json);
echo $json;
I have this php associative array.
array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
)
I would like to convert it into a json output using json_encode() that looks like this;
[{"Location_name":"Location_1","Link_name":"Link_1"},{"Location_name":"Location_2","Link_name":"Link_2"}]
How can this be done? The challenging part to me seems like how to add the Location_name and Link_name in front. Thank you very much.
<?php
// original array
$a = array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
);
// transform
$b = array();
foreach($a as $key=>$value) {
$b[] = array('Location_name'=>$key, 'Link_name'=>$value);
}
// output
echo json_encode($b);
?>
Result:
[{"Location_name":"Location_1","Link_name":"Link_1"},{"Location_name":"Location_2","Link_name":"Link_2"}]
You Can use StdClass anonymous Objects.
<?php
$newArray = array();
$array = array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
);
foreach ($array as $key => $value) {
$object = new StdClass();
$object->Location_name = $key;
$object->Link_name = $value;
$newArray[] = $object;
}
var_dump(json_encode($newArray));
So first things first:
convert it into a json output using json_encode() that looks like this
This is not possible. json_encode just encodes arrays to JSON, you need to do the formatting work yourself.
And on that note
array_map should do the trick.
Try this:
$arr = array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
);
$output = array_map(
function( $key, $val ){
return array(
"Location_name" => $key,
"Link_name" => $val
);
}, array_keys( $arr ), $arr );
echo json_encode( $output );
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?
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).
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);
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"}]
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);
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);
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.
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();
}