This should do the trick!
// convert object => json
$json = json_encode($myObject);
// convert json => object
$obj = json_decode($json);
Here's an example
$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";
$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}
print_r(json_decode($json));
// stdClass Object
// (
// [hello] => world
// [bar] => baz
// )
If you want the output as an Array instead of an Object, pass true to json_decode
print_r(json_decode($json, true));
// Array
// (
// [hello] => world
// [bar] => baz
// )
More about json_encode()
See also: json_decode()
Answer from maฤek on Stack OverflowConverting Object to JSON and JSON to Object in PHP, (library like Gson for Java) - Stack Overflow
A simple tool i wrote to convert your JSON into PHP classes
passing JSON object through PHP
Properly convert JSON with arrays to CSV
Any solution is going to be fragile as you're going from a more expressive to a less expressive format. As long as you can guarantee that all your nested objects (milestone, assignee and author) will always have the same order of elements and will never themselves contain an object or array, you should be able to simply implode them:
Instead of:
foreach ($line['author'] as $value)
{
array_push($line_array,$value);
}Use:
array_push($line_array, implode('|', $line['author']));
(Side note: it's generally better to do $myarr[] = 'val'; than array_push($myarr, 'val'). More readable and slightly faster.)
This should do the trick!
// convert object => json
$json = json_encode($myObject);
// convert json => object
$obj = json_decode($json);
Here's an example
$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";
$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}
print_r(json_decode($json));
// stdClass Object
// (
// [hello] => world
// [bar] => baz
// )
If you want the output as an Array instead of an Object, pass true to json_decode
print_r(json_decode($json, true));
// Array
// (
// [hello] => world
// [bar] => baz
// )
More about json_encode()
See also: json_decode()
for more extendability for large scale apps use oop style with encapsulated fields.
Simple way :-
class Fruit implements JsonSerializable {
private $type = 'Apple', $lastEaten = null;
public function __construct() {
$this->lastEaten = new DateTime();
}
public function jsonSerialize() {
return [
'category' => $this->type,
'EatenTime' => $this->lastEaten->format(DateTime::ISO8601)
];
}
}
echo json_encode(new Fruit()); //which outputs:
{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}
Real Gson on PHP :-
- http://jmsyst.com/libs/serializer
- http://symfony.com/doc/current/components/serializer.html
- http://framework.zend.com/manual/current/en/modules/zend.serializer.html
- http://fractal.thephpleague.com/ - serialize only
https://dani-gouken.github.io/json_to_php/