12-07-2012, 11:16 PM
вот сделал
может кому понадобится
может кому понадобится
class
PHP код:
<?php
class Json{
const ARRAY_TYPE = 0;
const OBJECT_TYPE = 1;
private $_array = array ();
private $_type = OBJECT_TYPE;
public function __construct($type = self::OBJECT_TYPE) {
$this->_type = $type;
}
public function add($value) {
$this->_array[] = $value;
$this->_type = self::ARRAY_TYPE;
}
public function get($i) {
return $this->_array[$i];
}
public function toArray() {
$object = new ArrayObject($this->_array);
$it = $object->getIterator();
$str .= '[';
while($it->valid()) {
$value = $it->current();
$it->next();
if(is_int($value) || $value instanceof Json || is_float($value))
$str .= $value;
else
$str .= "\"$value\"";
if($it->valid())
$str .= ',';
}
$str .= ']';
return $str;
}
public function toObject() {
$object = $this;
$str .= '{';
$str .= toJsonString($this);
$str .= '}';
return $str;
}
public function __toString() {
switch($this->_type) {
case self::ARRAY_TYPE: return $this->toArray();
case self::OBJECT_TYPE: return $this->toObject();
}
}
}
function toJsonString($json) {
$str = '';
foreach($json as $key => $value) {
$str .= "\"$key\"";
$str .= ':';
if(is_int($value) || $value instanceof Json || is_float($value))
$str .= $value;
else
$str .= "\"$value\"";
$str .= ',';
}
$str = substr($str, 0, strlen($str) - 1);
return $str;
}
пример
PHP код:
<?php
$array = new Json;
$array->add(0);
$array->add(1);
$array->add(2);
$array->add('test');
echo $array;
$object = new Json;
$object->test = 1;
$object->test = 'test dasd asdasd';
$object->array = new Json;
$object->array->add(0);
$object->array->add(1);
$object->array->add(2);
$object->object = new Json;
$object->object->key = 'value';
echo $object;