在PHP中使用逗号创建JS对象


Creating JS objects in PHP with commas in between

我正试图从PHP数组创建一个JS对象数组,但我很难找到在每个对象之间插入逗号的方法。

以下是我试图输出的内容:

var things = [
    {
        a: "foo",
        b: "bar"
    },  // Comma on this line
    {
        a: "moo",
        b: "car"
    }   // No comma on this line
];

到目前为止,我拥有的是:

var things = [
    <?php foreach ($things as $thing): ?>
    {
        a: "<?php echo $thing->getA(); ?>",
        b: "<?php echo $thing->getB(); ?>"
    }
    <?php endforeach; ?>
];

我想我可以求助于一些丑陋的东西,比如只运行一次的if语句:

<?php
    $i = 1;
    if ($i == 1) {
        echo '{';
        $i++;
    } else {
        echo ',{';
    }
?>

没有比这更干净/更好的方法吗?

类似。。。

$JSONData = json_encode($YourObject);

还有一个解码。。。

$OriginalObject = json_decode($JSONData);

如果您有一个PHP数组,并且想要在JavaScript中使用,则可以使用json_encode()

为什么不使用json_encode?

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

上面的示例将输出:{"a":1,"b":2,"c":3,"d":4,"e":5}

创建所需的结构作为PHP数组,然后使用json_encode(http://php.net/manual/en/function.json-encode.php)。

$plainThing = array();
foreach ($things as $thing) {
    $plainThing[] = array('a' => $thing.getA(), 'b' => $thing.getB());
}
echo json_encode($plainThing);