-3

嗨,这是我第一次尝试在 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);
}
4

1 回答 1

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;
于 2013-06-21T04:58:52.350 回答