PHP到Javascript多维数组(更新)

时间:2021-09-08 21:29:08

I'm trying to send a PHP array to Javascript.

我正在尝试向Javascript发送一个PHP数组。

So far i was only sending a single array in Json to my javascrpt ajax;

到目前为止,我只向我的javascript ajax发送了一个Json数组;

The PHP part so far works like that;

到目前为止,PHP部分是这样工作的;

If I have an error in my request;

如我的要求有错误;

$data[0] = 'false';
$data[1] = 'Error message';

If there is no error;

如果没有错误;

$data[0] = 'OK';
$data[1] = 'html content to display';

I want to send multidimensional array like;

我想发送多维数组;

 $data[0] = 'OK';
 $data[1] = 'html content to display';

 $data[1][0] = 'OK';
 $data[1][1] = 'another html content to display';

The Javascript function that passes the request;

传递请求的Javascript函数;

function load(action,container){
return new Promise(function (resolve, reject) {
    //alert(container);
    $.ajax({
        url: '/ajax.php',
        type: 'post',
        dataType: 'json',
        data: { 'query': 'true', 'action': action, 'container': container },
        success: function (data, status) {
            console.log(data[0] + ' : FOR ' + action);
            if (data[0] === 'false') {
                $("#errorBox").addClass('visible');
                 for (var i = 1; i < data.length; i++) {
                    $('#errMsg').append(data[i]+'<br>');
                    $('#console').prepend('<span class="consoleError">ERREUR : </span>' + data[i] + '<br>');
                }
                $("#errorBox").show();
            }
            else if (data[0] === 'OK') {
                resolve(data);
                $(document).ready(function () {
                 $('#console').prepend('<span class="consoleGood"> Statue: ' + data[0] + '</span> Requête: ' + action + ' Conteneur:' +container+ '<br>');
                data.splice(0,1);
            });
          }
            return;
        },
        error: function (xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
            return;
        }
    }); // end ajax call
});//promise 

};

};

On the PHP part I use ;

在我使用的PHP部分;

$data[0]= 'OK';
$data[1]= 'some content';
$data[1][0]= 'some more content';

echo json_encode($data);

I can get all the data contained in the first level of the array but not the second level.

我可以得到数组第一级的所有数据,但不是第二级。

The console log is showing me:

控制台日志显示的是:

"<div class="doc_css"><div class="doc_status">active</div><h1>Mon document</h1><p>Le corp de mon document</p><div class="doc_post_nfo">Originalement posté par 1 le 2016-02-13 15:25:35<div class="doc_edit">Modifier</div></div></div>"
length: 1
__proto__: Array[0]

So what do I have to do the get the second level of the array?

那么我需要做什么来得到数组的第二级呢?

3 个解决方案

#1


2  

I ran your PHP code and var_dump'ed the $data variable.

我运行了您的PHP代码并var_dump' $data变量。

<?php   
$data[0] = 'OK';
$data[1] = 'html content to display';

$data[1][0] = 'OK';
$data[1][1] = 'another html content to display';

var_dump($data);
?>

Here is what I got:

以下是我得到的:

array(2) {
  [0]=>
  string(2) "OK"
  [1]=>
  string(23) "Oaml content to display"
}

So your array is not multidimensional. Also note the first characters of the second element. Guess what happened?

所以你的数组不是多维的。还要注意第二个元素的第一个字符。猜猜发生了什么?

When you create a string in PHP, you can access individual characters as if the string was an array (well, technically, strings are character arrays). So:

当您在PHP中创建一个字符串时,您可以访问单个字符,就像字符串是一个数组一样(从技术上讲,字符串是字符数组)。所以:

<?php
$str = 'abcde';
$str[2] = 'k';
// Now $str contains "abkde"
?>

So that's what happened. You changed the first and then the second character of $data[1].

这是发生了什么事。您更改了$data[1]的第一个和第二个字符。

<?php
$data[1] = 'html content to display';
$data[1][0] = 'OK';
// Now $data[1] contains "Otml content to display"
$data[1][1] = 'another html content to display';
// Now $data[1] contains "Oaml content to display"
?>

A multi-dimensional array is an array containing arrays. PHP create arrays on the spot when you use the bracket notation, but of course if the variable (or array cell) alreay contained a string it interprets the brackets as an access to individual characters.

多维数组是一个包含数组的数组。当您使用方括号符号时,PHP会当场创建数组,但是当然,如果变量(或数组单元格)包含一个字符串,它会将方括号解释为对单个字符的访问。

This works:

如此:

<?php   
$data[0][0] = 'OK';
$data[0][1] = 'html content to display';

$data[1][0] = 'OK';
$data[1][1] = 'another html content to display';

echo json_encode($data);
?>

It prints [["OK","html content to display"],["OK","another html content to display"]], which the Javascript code can parse and use after retrieving.

它打印[[OK], "html内容显示"],["OK","另一个html内容显示"],Javascript代码可以在检索后解析和使用。

#2


1  

I'm not going to repeat your entire scenario with this answer, but I've had the same need .. to get my PHP array's into javascript. All I did was use PHP to create a Javascript function (or simple JS code) that set the array values. Here's a conceptual example. You can apply to your situation:

我不会用这个答案重复你的整个场景,但我也有同样的需要。将PHP数组转换为javascript。我所做的就是使用PHP创建一个Javascript函数(或简单的JS代码)来设置数组值。这是一个概念的例子。你可以申请你的情况:

First, the basic PHP array:

首先,基本的PHP数组:

<?php
$a[1] = "Mike";
$a[2] = "Jim";
$a[3] = "Mark";
$a[4] = "George";
?>

To get this array in to Javascript, I would do something like:

要将这个数组输入到Javascript中,我需要做如下操作:

<?php
print "<script type='text/javascript'>\n";
   foreach ($a as $key => $val) {
      print "a[$key] = \"".$val."\";\n";
   }
print "</script>\n";
?>

This produces:

这产生:

<script type='text/javascript'>
a[1] = "Mike";
a[2] = "Jim";
a[3] = "Mark";
a[4] = "George";
</script>

It's a fudgy way to do things but it works. Of course this is a very stupid/basic example but it does show one way to get a PHP array into JS.

这是一种复杂的做事方式,但它确实有效。当然,这是一个非常愚蠢的/基本的示例,但它确实展示了将PHP数组转换为JS的一种方法。

#3


1  

maybe you can do it better this way

也许你可以用这种方法做得更好

$data = [['code'=>true,'message'=>'Error message'],['code'=>'OK','message'=>'Other message']];

then do

然后做

json_encode($data);

on javascript you can get (by convert to json via ajax like you did)

在javascript上你可以得到(通过像你那样通过ajax将json转换成json)

data[0].code // will be true
data[1].message // will be 'Other message'

#1


2  

I ran your PHP code and var_dump'ed the $data variable.

我运行了您的PHP代码并var_dump' $data变量。

<?php   
$data[0] = 'OK';
$data[1] = 'html content to display';

$data[1][0] = 'OK';
$data[1][1] = 'another html content to display';

var_dump($data);
?>

Here is what I got:

以下是我得到的:

array(2) {
  [0]=>
  string(2) "OK"
  [1]=>
  string(23) "Oaml content to display"
}

So your array is not multidimensional. Also note the first characters of the second element. Guess what happened?

所以你的数组不是多维的。还要注意第二个元素的第一个字符。猜猜发生了什么?

When you create a string in PHP, you can access individual characters as if the string was an array (well, technically, strings are character arrays). So:

当您在PHP中创建一个字符串时,您可以访问单个字符,就像字符串是一个数组一样(从技术上讲,字符串是字符数组)。所以:

<?php
$str = 'abcde';
$str[2] = 'k';
// Now $str contains "abkde"
?>

So that's what happened. You changed the first and then the second character of $data[1].

这是发生了什么事。您更改了$data[1]的第一个和第二个字符。

<?php
$data[1] = 'html content to display';
$data[1][0] = 'OK';
// Now $data[1] contains "Otml content to display"
$data[1][1] = 'another html content to display';
// Now $data[1] contains "Oaml content to display"
?>

A multi-dimensional array is an array containing arrays. PHP create arrays on the spot when you use the bracket notation, but of course if the variable (or array cell) alreay contained a string it interprets the brackets as an access to individual characters.

多维数组是一个包含数组的数组。当您使用方括号符号时,PHP会当场创建数组,但是当然,如果变量(或数组单元格)包含一个字符串,它会将方括号解释为对单个字符的访问。

This works:

如此:

<?php   
$data[0][0] = 'OK';
$data[0][1] = 'html content to display';

$data[1][0] = 'OK';
$data[1][1] = 'another html content to display';

echo json_encode($data);
?>

It prints [["OK","html content to display"],["OK","another html content to display"]], which the Javascript code can parse and use after retrieving.

它打印[[OK], "html内容显示"],["OK","另一个html内容显示"],Javascript代码可以在检索后解析和使用。

#2


1  

I'm not going to repeat your entire scenario with this answer, but I've had the same need .. to get my PHP array's into javascript. All I did was use PHP to create a Javascript function (or simple JS code) that set the array values. Here's a conceptual example. You can apply to your situation:

我不会用这个答案重复你的整个场景,但我也有同样的需要。将PHP数组转换为javascript。我所做的就是使用PHP创建一个Javascript函数(或简单的JS代码)来设置数组值。这是一个概念的例子。你可以申请你的情况:

First, the basic PHP array:

首先,基本的PHP数组:

<?php
$a[1] = "Mike";
$a[2] = "Jim";
$a[3] = "Mark";
$a[4] = "George";
?>

To get this array in to Javascript, I would do something like:

要将这个数组输入到Javascript中,我需要做如下操作:

<?php
print "<script type='text/javascript'>\n";
   foreach ($a as $key => $val) {
      print "a[$key] = \"".$val."\";\n";
   }
print "</script>\n";
?>

This produces:

这产生:

<script type='text/javascript'>
a[1] = "Mike";
a[2] = "Jim";
a[3] = "Mark";
a[4] = "George";
</script>

It's a fudgy way to do things but it works. Of course this is a very stupid/basic example but it does show one way to get a PHP array into JS.

这是一种复杂的做事方式,但它确实有效。当然,这是一个非常愚蠢的/基本的示例,但它确实展示了将PHP数组转换为JS的一种方法。

#3


1  

maybe you can do it better this way

也许你可以用这种方法做得更好

$data = [['code'=>true,'message'=>'Error message'],['code'=>'OK','message'=>'Other message']];

then do

然后做

json_encode($data);

on javascript you can get (by convert to json via ajax like you did)

在javascript上你可以得到(通过像你那样通过ajax将json转换成json)

data[0].code // will be true
data[1].message // will be 'Other message'