简体   繁体   English

将 php 数组转换为 Javascript

[英]Convert php array to Javascript

How can I convert a PHP array in a format like this如何以这样的格式转换 PHP 数组

Array
(
    [0] => 001-1234567
    [1] => 1234567
    [2] => 12345678
    [3] => 12345678
    [4] => 12345678
    [5] => AP1W3242
    [6] => AP7X1234
    [7] => AS1234
    [8] => MH9Z2324
    [9] => MX1234
    [10] => TN1A3242
    [11] => ZZ1234
)

to a Javascript array in the format below?到以下格式的 Javascript 数组?

var cities = [
    "Aberdeen",
    "Ada",
    "Adamsville",
    "Addyston",
    "Adelphi",
    "Adena",
    "Adrian",
    "Akron",
    "Albany"
];

I'm going to assume that the two arrays you've given for PHP and JS are not related, and they're just examples of how arrays look in the two languages.我将假设您为 PHP 和 JS 提供的两个数组不相关,它们只是数组在两种语言中的外观示例。 Clearly you're not going to be able to convert those sequences of letters and numbers into those city names.显然,您无法将这些字母和数字序列转换为城市名称。

PHP provides a function to convert PHP arrays into Javascript code: json_encode() . PHP 提供了将 PHP 数组转换为 Javascript 代码的函数: json_encode() (technically, it's JSON format; JSON stands for JavaScript Object Notation) (从技术上讲,它是 JSON 格式;JSON 代表 JavaScript Object Notation)

Use it like this:像这样使用它:

<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>

See also the manual page I linked above for more information.另请参阅我上面链接的手册页以获取更多信息。

Note that json_encode() is only available in PHP 5.2 and up, so if you're using an older version, you'll need to use an existing one -- the PHP manual page also includes comments with functions written by people who needed it.请注意, json_encode()仅在 PHP 5.2 及更高版本中可用,因此如果您使用的是旧版本,则需要使用现有版本——PHP 手册页还包含对需要它的人编写的函数的注释. (but that said, if you're using anything older than PHP 5.2 you should upgrade ASAP) (不过话说回来,如果你使用的是 PHP 5.2 之前的版本,你应该尽快升级)

Spudley's answer is fine . Spudley 的回答很好

Security Notice: The following should not be necessary any longer for you安全注意事项:您不再需要以下内容

If you don't have PHP 5.2 you can use something like this:如果你没有 PHP 5.2,你可以使用这样的东西:

function js_str($s)
{
    return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}

function js_array($array)
{
    $temp = array_map('js_str', $array);
    return '[' . implode(',', $temp) . ']';
}

echo 'var cities = ', js_array($php_cities_array), ';';

愚蠢而简单:

var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];

You do not have to call parseJSON since the output of json_encode is a javascript literal.您不必调用 parseJSON,因为json_encode输出是 javascript 文字。 Just assign it to a js variable.只需将它分配给一个 js 变量。

<script type="text/javascript">
    //Assign php generated json to JavaScript variable
    var tempArray = <?php echo json_encode($php_array); ?>;

   //You will be able to access the properties as 
    alert(tempArray[0].Key);
</script>

you can convert php arrays into javascript using php's json_encode function您可以使用 php 的json_encode函数将 php 数组转换为 javascript

 <?php $phpArray = array( 0 => 001-1234567, 1 => 1234567, 2 => 12345678, 3 => 12345678, 4 => 12345678, 5 => 'AP1W3242', 6 => 'AP7X1234', 7 => 'AS1234', 8 => 'MH9Z2324', 9 => 'MX1234', 10 => 'TN1A3242', 11 => 'ZZ1234' ) ?>
<script type="text/javascript">

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

    for(var i=0;i<12;i++){
        alert(jArray[i]);
    }

 </script>

I find the quickest and easiest way to work with a PHP array in Javascript is to do this:我发现在 Javascript 中使用 PHP 数组的最快和最简单的方法是这样做:

PHP: PHP:

$php_arr = array('a','b','c','d');

Javascript: Javascript:

//this gives me a JSON object
js_arr = '<?php echo JSON_encode($php_arr);?>';


//Depending on what I use it for I sometimes parse the json so I can work with a straight forward array:
js_arr = JSON.parse('<?php echo JSON_encode($php_arr);?>');

so simple ...!很简单 ...!

use this method:使用这个方法:

<?php echo json_encode($your_array); ?>; 

in laravel blade {{ }} use this method:在 Laravel Blade {{ }} 中使用此方法:

{{ str_replace('&quot;', '', json_encode($your_array)) }} 

working for associated and unassociated array.为关联和非关联数组工作。

Is very simple I use this way:很简单我用这种方式:

JAVASCRIPT :爪哇脚本

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

Convert PHP array to JavascriptPHP 数组转换为 Javascript

Regards!问候!

u can also do in this way你也可以这样做

<script>  
    <?php 
        $php_array = array('abc','def','ghi');
    ?>  
    var array_code = <?php echo json_encode($php_array); ?>;
    console.log(array_code);
</script>

For a multidimensional array in PHP4 you can use the following addition to the code posted by Udo G:对于 PHP4 中的多维数组,您可以在 Udo G 发布的代码中添加以下内容:

function js_str($s) {
   return '"'.addcslashes($s, "\0..\37\"\\").'"';
}

function js_array($array, $keys_array) {
  foreach ($array as $key => $value) {
    $new_keys_array = $keys_array;
    $new_keys_array[] = $key;
    if(is_array($value)) {          
      echo 'javascript_array';
      foreach($new_keys_array as $key) {
        echo '["'.$key.'"]';
      }
      echo ' = new Array();';

      js_array($value, $new_keys_array);
    } else {
      echo 'javascript_array';
      foreach($new_keys_array as $key) {
        echo '["'.$key.'"]';
      }
      echo ' = '.js_str($value).";";                        
    }
  } 
}

echo 'var javascript_array = new Array();';
js_array($php_array, array());

This is my function.这是我的职能。 JavaScript must be under PHP otherwise use SESSION. JavaScript 必须在 PHP 下,否则使用 SESSION。

<?php
 $phpArray=array(1,2,3,4,5,6);
?>

<div id="arrayCon" style="width:300px;"></div>

<script type="text/javascript">
var jsArray = new Array();
<?php
 $numArray=count($phpArray);
 for($i=0;$i<$numArray;$i++){
  echo "jsArray[$i] = ". $phpArray[$i] . ";\n";
 }
?>
$("#arrayCon").text(jsArray[1]);
</script>

Last row can be ....text(jsArray);最后一行可以是 ....text(jsArray); and will be shown "1,2,3,4,5,6"并将显示“1,2,3,4,5,6”

I use a fake php array我使用了一个假的php 数组

<?php 
       // instead to create your array like this
       $php_array = ["The","quick","brown","fox","jumps","over","the","lazy","dog"];

       // do it like this (a simple variable but with separator)
       $php_fake_array = "The,quick,brown,fox,jumps,over,the,lazy,dog";
?>

<script type="text/javascript">

        // use the same separator for the JS split() function
        js_array = '<?php echo $php_fake_array; ?>'.split(',');

</script>

if ever your array is unknown (already made)如果您的数组未知(已制作)

<?php 
        $php_array = file('my_file.txt');
        $php_fake_array = "";

        // transform your array with concatenate like this
        foreach ($php_array as $cell){

            // since this array is unknown, use clever separator
            $php_fake_array .= $cell.",,,,,"; 
        }
?>

<script type="text/javascript">

        // use the same separator for the JS split() function
        js_array = '<?php echo $php_fake_array; ?>'.split(',,,,,');

</script>

It can be done in a safer way.它可以以更安全的方式完成。

If your PHP array contains special characters, you need to use rawurlencode() in PHP and then use decodeURIComponent() in JS to escape those.如果您的 PHP 数组包含特殊字符,则需要在 PHP 中使用 rawurlencode() ,然后在 JS 中使用 decodeURIComponent() 来转义这些字符。 And parse the JSON to native js.并将 JSON 解析为原生 js。 Try this:尝试这个:

var data = JSON.parse(
        decodeURIComponent(
            "<?=rawurlencode(json_encode($data));?>"
        )
    );

console.log(data);

I had the same problem and this is how i done it.我遇到了同样的问题,这就是我的做法。

/*PHP FILE*/

<?php

$data = file_get_contents('http://yourrssdomain.com/rss');
$data = simplexml_load_string($data);

$articles = array();

foreach($data->channel->item as $item){

    $articles[] = array(

        'title' => (string)$item->title,
        'description' => (string)$item ->description,
        'link' => (string)$item ->link, 
        'guid' => (string)$item ->guid,
        'pubdate' => (string)$item ->pubDate,
        'category' => (string)$item ->category,

    );  
}

// IF YOU PRINT_R THE ARTICLES ARRAY YOU WILL GET THE SAME KIND OF ARRAY THAT YOU ARE GETTING SO I CREATE AN OUTPUT STING AND WITH A FOR LOOP I ADD SOME CHARACTERS TO SPLIT LATER WITH JAVASCRIPT

$output="";

for($i = 0; $i < sizeof($articles); $i++){

    //# Items
    //| Attributes 

    if($i != 0) $output.="#"; /// IF NOT THE FIRST

// IF NOT THE FIRST ITEM ADD '#' TO SEPARATE EACH ITEM AND THEN '|' TO SEPARATE EACH ATTRIBUTE OF THE ITEM 

    $output.=$articles[$i]['title']."|";
    $output.=$articles[$i]['description']."|";
    $output.=$articles[$i]['link']."|";
    $output.=$articles[$i]['guid']."|";
    $output.=$articles[$i]['pubdate']."|";
    $output.=$articles[$i]['category'];
}

echo $output;

?>
/* php file */


/*AJAX COMUNICATION*/

$(document).ready(function(e) {

/*AJAX COMUNICATION*/

var prodlist= [];
var attrlist= [];

  $.ajax({  
      type: "get",  
      url: "php/fromupnorthrss.php",  
      data: {feeding: "feedstest"},
      }).done(function(data) {

        prodlist= data.split('#');

        for(var i = 0; i < prodlist.length; i++){

            attrlist= prodlist[i].split('|');

            alert(attrlist[0]); /// NOW I CAN REACH EACH ELEMENT HOW I WANT TO. 
        }
   });
});

I hope it helps.我希望它有帮助。

把事情简单化 :

var jsObject = JSON.parse('<?= addslashes(json_encode($phpArray)) ?>');

If you need a multidimensional PHP array to be printed directly into the html page source code, and in an indented human-readable Javascript Object Notation (aka JSON) fashion, use this nice function I found in http://php.net/manual/en/function.json-encode.php#102091 coded by somebody nicknamed "bohwaz".如果您需要将多维 PHP 数组直接打印到 html 页面源代码中,并以缩进的人类可读 Javascript 对象表示法(又名 JSON)方式打印,请使用我在http://php.net/manual 中找到的这个不错的函数/en/function.json-encode.php#102091由昵称为“bohwaz”的人编码。

<?php

function json_readable_encode($in, $indent = 0, $from_array = false)
{
    $_myself = __FUNCTION__;
    $_escape = function ($str)
    {
        return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
    };

    $out = '';

    foreach ($in as $key=>$value)
    {
        $out .= str_repeat("\t", $indent + 1);
        $out .= "\"".$_escape((string)$key)."\": ";

        if (is_object($value) || is_array($value))
        {
            $out .= "\n";
            $out .= $_myself($value, $indent + 1);
        }
        elseif (is_bool($value))
        {
            $out .= $value ? 'true' : 'false';
        }
        elseif (is_null($value))
        {
            $out .= 'null';
        }
        elseif (is_string($value))
        {
            $out .= "\"" . $_escape($value) ."\"";
        }
        else
        {
            $out .= $value;
        }

        $out .= ",\n";
    }

    if (!empty($out))
    {
        $out = substr($out, 0, -2);
    }

    $out = str_repeat("\t", $indent) . "{\n" . $out;
    $out .= "\n" . str_repeat("\t", $indent) . "}";

    return $out;
}

?>       

Below is a pretty simple trick to convert PHP array to JavaScript array:下面是将 PHP 数组转换为 JavaScript 数组的一个非常简单的技巧:

$array = array("one","two","three");

JS below: JS如下:

// Use PHP tags for json_encode()

var js_json =  json_encode($array);
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string);

alert(js_json_array.length);

It works like a charm.它就像一个魅力。

Many good and complex solutions are here and this is a way to doing it without parsing json in user side.这里有许多好的和复杂的解决方案,这是一种无需在用户端解析 json 的方法。

$mtc=array();
$replace=array();

$x = json_encode($thearray);

preg_match_all('/"[a-z0-9_]*":/',$x,$mtc);

foreach($mtc[0] as $v){
    array_push($replace,str_replace('"','',$v));
}
    
$x = str_replace($mtc[0],$replace,$x);

echo '<script type="text/javascript">x='.$x.';console.log(x);</script>';

This works with both indexed and associative arrays(any combination) which has multiple levels, and no need for user side json parsing.这适用于具有多个级别的索引和关联数组(任何组合),并且不需要用户端 json 解析。

For Laravel , Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks.对于Laravel ,Blade {{ }}语句会通过 PHP 的 htmlspecialchars 函数自动发送,以防止 XSS 攻击。 Your data to be unescaped , you can use the following syntax :您的数据要转义,您可以使用以下语法:

const jsArray = {!! str_replace('&quot;', '', json_encode($array)) !!};

For Laravel user: use @json对于 Laravel 用户:使用@json

var cities = @json($data);

As explained in official docs: https://laravel.com/docs/8.x/blade#rendering-json :如官方文档中所述: https://laravel.com/docs/8.x/blade#rendering-json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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