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?

0

4 Answers 4

5

Something like...

$JSONData = json_encode($YourObject);

There's also a decode...

$OriginalObject = json_decode($JSONData);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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}

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.