2

I'm trying to create an array of JS objects from a PHP array, but I'm struggling to find a way to insert commas in between each object.

Here's what I'm trying to output:

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

And here is what I have so far:

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

I suppose I could resort to something ugly, like an if statement that only runs once:

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

Is there not a cleaner/better way to do this?

4

4 に答える 4

5

何かのようなもの...

$JSONData = json_encode($YourObject);

デコードもあります...

$OriginalObject = json_decode($JSONData);
于 2012-07-25T11:38:07.983 に答える
1

PHP 配列があり、JavaScript で使用できるものが必要な場合は、次を使用できます。json_encode()

于 2012-07-25T11:38:28.510 に答える
1

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}

于 2012-07-25T11:39:09.337 に答える
0

必要な構造を 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);
于 2012-07-25T11:41:43.970 に答える