简体   繁体   中英

How can get values from php array using jquery or javascript?

I trying to get data from php array and put in java-script variable. Follwoing are the php arrays.

Array Name

Array
(
    [0] => username
    [1] => byusers
)

Array Value

Array
(
    [0] => user
    [1] => 1
)

What I have Try tried

Get php array value in javascript variable

var DATATABLE_SEARCH_NAMES      = new Array( "<?php echo (is_array($DATATABLE_SEARCH_DATA_NAMES)) ? $DATATABLE_SEARCH_DATA_NAMES['names'] : 0;?>");
var DATATABLE_SEARCH_VALUES     = new Array( "<?php echo (is_array($DATATABLE_SEARCH_DATA_VALUE)) ? $DATATABLE_SEARCH_DATA_VALUE['values'] : 0;?>");

say, you have a PHP array as this:

$arr = array("key1"=>"foo","key2"=>"bar");

the easiest way to put it to javascript is this:

var arr = <?php echo json_encode($arr); ?>;

ending with a JSON object.

This should do what you ask, it is just a case of converting the PHP arrays to a form that javascript can understand. You can use json_encode() to do that.

$DATATABLE_SEARCH_DATA_NAMES = array('username','byusers');
$DATATABLE_SEARCH_DATA_VALUE = array('user', 1);

$js1 = json_encode($DATATABLE_SEARCH_DATA_NAMES);
$js2 = json_encode($DATATABLE_SEARCH_DATA_VALUE);

//echo $js1.PHP_EOL;
//echo $js2.PHP_EOL;

echo "<script>\n";
echo 'var names = ' . $js1 . ";\n";
echo 'var values = ' . $js2 . ";\n";
echo "</script>\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM