gpt4 book ai didi

php - 在 PHP 中用逗号创建 JS 对象

转载 作者:行者123 更新时间:2023-12-02 07:40:34 25 4
gpt4 key购买 nike

我正在尝试从 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 - 在 PHP 中用逗号创建 JS 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11648829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com