使用类,数组,json和php的问题

时间:2013-06-20 23:00:32

标签: php arrays json

嗨,这是我第一次尝试在PHP中创建一些代码,这花了我很长时间,但我能够将数据转换为xml。现在我需要创建一个JSON对象,但它并不顺利。最大的问题是尝试在PHP中创建一个新类(我不知道我做了什么是否正常)以及这是否是附加列表的正确方法。我认为它有些好,但对我来说因为我只使用java和c#看起来有点疯狂。我想我做错了什么。显示错误的行是$array['data']->attach( new Cake($name,$ingredients,$prepare,$image));,但我不知道我做错了什么。 我还没有编写包含并将数组转换为json

的行

由于

//opens the file, if it doesn't exist, it creates
$pointer = fopen($file, "w");

// writes into json


$cake_list['data'] = new SplObjectStorage();
for ($i = 0; $i < $row; $i++) {

    // Takes the SQL data
    $name = mysql_result($sql, $i, "B.nome");
    $ingredients = mysql_result($sql, $i, "B.ingredientes");
    $prepare = mysql_result($sql, $i, "B.preparo");
    $image = mysql_result($sql, $i, "B.imagem");

    // assembles the xml tags
    // $content = "{";

    // $content .= "}";

    $array['data']->attach( new Cake($name,$ingredients,$prepare,$image));
    // $content .= ",";
    // Writes in file
    // echo $content;
    $content = json_encode($content);

    fwrite($pointer, $content);
    // echo $content;
} // close FOR

echo cake_list;

// close the file
fclose($pointer);

// message
// echo "The file <b> ".$file."</b> was created successfully !";
// closes IF($row)

class Cake {
    var $name;
    var $ingredients;
    var $prepare;
    var $image;

    public function __construct($name, $ingredients, $prepare, $image)
    {
        $this->name = $name;
        $this->ingredients = $ingredients;
    $this->prepare = $prepare;
    $this->image = $image;
    }
}

function create_instance($class, $arg1, $arg2, $arg3, $arg4)
{
    $reflection_class = new ReflectionClass($class);
    return $reflection_class->newInstanceArgs($arg1, $arg2,$arg3, $arg4);
}

1 个答案:

答案 0 :(得分:0)

您遇到的错误是因为您的意思是$array['data'] $cake_list['data']所以请将错误行更改为:

$cake_list['data']->attach(new Cake($name, $ingredients, $prepare, $image));

创建JSON对象(或者更准确地说是JSON对象的字符串表示)的简单方法也是一种简单的方法:

$array = array(
    'name' => $name,
    'ingredients' => $ingredients,
    'prepare' => $prepare,
    'image' => $image
);

$json = json_encode($array);

您还可以创建简单易用的对象:

$myObject = new stdClass(); // stdClass() is generic class in PHP

$myObject->name        = $name;
$myObject->ingredients = $ingredients;
$myObject->prepare     = $prepare;
$myObject->image       = $image;
相关问题