0

I'd like to pass arrays through JSON like this:

<?php

for(i=0;i<5;i++) {
  $arrayA[i] = "A" . i;
  $arrayB[i] = "B" . i;
}

echo json_encode($arrayA,$arrayB);

?>

I know it's not possible, but is there other way to pass dynamicly loaded arrays and read them in javascript after that?

2
  • what about this echo json_encode(array($arrayA,$arrayB)); Commented Jul 19, 2012 at 9:01
  • @AdamWaite: That's JavaScript, he's asking for a PHP solution ;-) Commented Jul 19, 2012 at 9:03

4 Answers 4

2

Just put both array in another array.

$returnArr = array($arrayA,$arrayB);
echo json_encode($returnArr);

On JS side just decode with a library of your choice and access the returned array like any normal array.

Sign up to request clarification or add additional context in comments.

Comments

2
echo json_encode(array('arrayA' => $arrayA, 'arrayB' => $arrayA));

Comments

1

Just create wrapper for your arrays:

for(i=0;i<5;i++) {
    $arrayA[i] = "A" . i;
    $arrayB[i] = "B" . i;
}
$arrayC = array($arrayA,$arrayB);
echo json_encode($arrayC);

On jQuery side:

$.getJSON('ajax/yourPhpFile.php', function(data) {
    $.each(data, function(key, val) {
        // each `val` is one of the arrays you passed from php
    });
});

Comments

0

You can use AJAX to load up a script that will return a PHP generated array. If you're using jQuery, you call it using either $.get() or $.getJSON(). You can read up on PHP JSON manual here http://php.net/manual/en/book.json.php and on jQuery .getJson() function here http://api.jquery.com/jQuery.getJSON/

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.