0

Let's say I have a table

[table fruits]
--------+------------+
ID [PK] | fruit      |
--------+------------+
1       | Orange     |
2       | Banana     |
3       | Coconut    |

and I need to save a list of IDs and names in a JS array, like for example:

var fkOptionList = [[1]['Orange'],[2]['Banana'],[3]['Coconut']]

in PHP I achieved this by:

        $fkOptionTableR = $fkOptionTableQ->result_array();

        $fkOption2dArray[] = array();
        $i = 0;
        $j = 0;

        foreach ($fkOptionTableR as $array) {
          foreach ($array as $row) {
          $fkOption2dArray[$i][$j] = $row;
            $j++;
          }
          $i++;
          $j = 0;
        }

which results in (according to var_dump):

array(3) { 
[0]=> array(2) { [0]=> string(1) "1" [1]=> string(6) "Orange" } 
[1]=> array(2) { [0]=> string(1) "2" [1]=> string(6) "Banana" } 
[2]=> array(2) { [0]=> string(1) "3" [1]=> string(7) "Coconut" } 
} 

I would need that array in my JS script, but the problem is it's in other file (above PHP script is loaded once by a CI's controller). Is there a way to pass it?

3
  • 2
    php.net/manual/en/function.json-encode.php Commented Oct 22, 2013 at 16:49
  • Your fkOptionList is a syntax error. Commented Oct 22, 2013 at 16:50
  • @RocketHazmat - right, it meant to be fkOptionList = [[1, 'Orange'],[2, 'Banana'],[3, 'Coconut']] Commented Oct 22, 2013 at 17:06

1 Answer 1

5

In PHP

$yourArray = json_encode($fkOptionTableR);

In JAVASCRIPT

var twoDarray = <?php echo $yourArray ?>
Sign up to request clarification or add additional context in comments.

5 Comments

the second doesn't work (unexpected <), anyway I have my json_encoded array in a div, but don't know how can I paste its content to a JS variable body so that it will become an array?
use var array = $("#That Div Id").text();
I've tried, it treats var array like a string then, not as an array
when I use alert(fkOptionList[1]); it returns [ instead of array's element
I've made a workaround, creating JS var in PHP script, instead of echoing it in a div. Thanks for help.

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.