emil.c
emil.c

Reputation: 2018

How to pass arrays through JSON php

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?

Upvotes: 0

Views: 401

Answers (4)

Zagor23
Zagor23

Reputation: 1963

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

Upvotes: 1

Kasia Gogolek
Kasia Gogolek

Reputation: 3414

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/

Upvotes: 0

mdziekon
mdziekon

Reputation: 3627

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

Upvotes: 2

enricog
enricog

Reputation: 4273

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.

Upvotes: 2

Related Questions