Jezen Thomas
Jezen Thomas

Reputation: 13800

Creating JS objects in PHP with commas in between

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?

Upvotes: 2

Views: 119

Answers (4)

Prinzhorn
Prinzhorn

Reputation: 22518

Create the desired structure as PHP Arrays and then use 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);

Upvotes: 0

message
message

Reputation: 4603

Why dont you use json_encode?

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

echo json_encode($arr);
?>

The above example will output: {"a":1,"b":2,"c":3,"d":4,"e":5}

Upvotes: 1

Mitya
Mitya

Reputation: 34596

If you have a PHP array and want something usable in JavaScript, you can use json_encode()

Upvotes: 1

Basic
Basic

Reputation: 26766

Something like...

$JSONData = json_encode($YourObject);

There's also a decode...

$OriginalObject = json_decode($JSONData);

Upvotes: 5

Related Questions