简体   繁体   English

将PHP数组转换为JavaScript

[英]Converting PHP array to JavaScript

I know there have been many questions regarding converting PHP arrays to Javascript and the standard answer is along the lines of: 我知道有很多关于将PHP数组转换为Javascript的问题,标准答案大致如下:

tempary=<?php echo json_encode($tmpary); ?>;

However, when I try to access the array, I can't access the elements. 但是,当我尝试访问数组时,无法访问元素。 eg 例如

document.write(tempary[2]);                                 //debug

even though I know that there is a 3rd element. 即使我知道有第三个要素。

Here is the actual code: 这是实际的代码:

global $wpdb;
$query="SELECT * FROM wp_ta_members";
$member_table=$wpdb->get_results($query);
echo "<p>Size of wp_ta_members table is " . count($member_table) . "</p>";      //debug
?>
<script type="text/javascript">
var members = [];
var tempary = [];
</script>
<?php
foreach ($member_table as $member_row)
    {
    $tmpary=array($member_row->member_id,
    ($member_row->current==1)?"current":"not a member",
    $member_row->date_joined,
    $member_row->title,
    $member_row->first_names,
    $member_row->last_names)
    ?>
    <script type="text/javascript">
    tempary=<?php echo json_encode($tmpary); ?>;
    document.write(tempary[2]);                                 //debug
    console.log(tempary);                                   //debug
    members.push(tempary.concat());
</script>
<?php   }
?>

You will notice that I am actually creating an array of arrays which I process later using a loop of: 您会注意到,我实际上是在创建一个数组数组,稍后使用以下循环处理:

for (mem in members)
{
document.write(workary.length + " " + members.length + " " + mem.length + " " + members[1] + "<br />");     //debug
document.write(mem[1] + " " + mem[2] + " " + mem[3] + " " + mem[4] +"<br />");      //debug
}

However, all I get for tempary[0] is "1" and for any other elements- "undefined". 但是,对于tempary [0],我得到的都是“ 1”,对于其他任何元素,都得到了“未定义”。

If I output tempary itself, I get a string of all the elements separated by commas. 如果我输出tempary本身,则会得到一串所有用逗号分隔的元素。

What I am I missing? 我想念我什么? I want tempary to be a proper JavaScript array. 我希望暂时成为一个合适的JavaScript数组。

Sorry to come back yet again, but this is still not working 很抱歉再次回来,但这仍然无法正常工作

I have added the following code to the script just to check out the concept: 我将以下代码添加到脚本中只是为了检查概念:

var a1 = [100, "scooby", "doo"];
var a2 = [200, "soup", "dragon"];
var a3 = [];
a3.push(a1);
a3.push(a2);
console.log(a3);
console.log(a3[0]);
console.log(a3[1]);
console.log(a3[1][0] + " " + a3[1][1]);

And the result is: 结果是:

[Array[3], Array[3]]
[100, "scooby", "doo"]
[200, "soup", "dragon"]
200 soup

which is correct! 哪个是对的!

When I run my real code, and execute the lines (within a loop): 当我运行我的真实代码并执行这些行时(在一个循环内):

    console.log(tempary);                                   //debug
    members.push(tempary);

I get the result: 我得到结果:

["78", "current", "2014-01-01", "", "Fred", "Bloggs"]

which is also correct (although I would prefer the "78" to be stored as a number rather than a string - but that's another story). 这也是正确的(尽管我更愿意将“ 78”存储为数字而不是字符串-但这是另一回事了)。

When however, I execute a loop to print out the contents of the array of arrays using: 但是,当我执行循环以使用以下命令打印出数组的内容:

for (mem in members)
    {
    console.log(members.length + " " + mem.length + " " + members[1]);      //debug
    console.log(mem + " " + mem[0] + " " + mem[1] + " " + mem[2] + " " + mem[3] + " " + mem[4]);        //debug

    }

I get a log list repeating: 我得到一个重复的日志列表:

1333 1 8000,current,2014-01-01,Ms,Joe,Soap
0 0 undefined undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
1 1 undefined undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
2 2 undefined undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
3 3 undefined undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
4 4 undefined undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
5 5 undefined undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
6 6 undefined undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
7 7 undefined undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
8 8 undefined undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
9 9 undefined undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
10 1 0 undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
11 1 1 undefined undefined undefined
1333 1 8000,current,2014-01-01,Ms,Joe,Soap
12 1 2 undefined undefined undefined

where 1333 is the number of arrays in the members array. 其中1333是成员数组中的数组数。 Joe Soap is the last member in the list. Joe Soap是列表中的最后一个成员。 Why console.log(mem); 为什么使用console.log(mem); produces an incrementing number I have no idea. 产生一个递增的数字,我不知道。 A further peculiar thing happens when this number goes double digit eg 12 makes mem[0] = 1 and mem[1] =2 !! 当此数字变为两位数时,还会发生另一种特殊的情况,例如12使mem [0] = 1和mem [1] = 2 !! The remaining elements of mem are "undefined". mem的其余元素为“未定义”。

Just for completeness, here is the entire script: 仅出于完整性考虑,以下是整个脚本:

<?php
/***** php and javascript to administer member details *****/

// **** get entire members table into a variable
    global $wpdb;
    $query="SELECT * FROM wp_ta_members";
    $member_table=$wpdb->get_results($query);
    echo "<p>Size of wp_ta_members table is " . count($member_table) . "</p>";  //debug
?>
<script type="text/javascript">
    var members = [2000];
    var tempary = [];
    var a1 = ["100", "scooby", "doo"];      //test
    var a2 = ["200", "soup", "dragon"];     //test
    var a3 = [];        //test
    a3.push(a1);        //test
    a3.push(a2);        //test
    console.log(a3);
    console.log(a3[0]);
    console.log(a3[1]);
    console.log(a3[1][0] + " " + a3[1][1]);
<?php
    foreach ($member_table as $member_row)
        {
        $tmpary=array($member_row->member_id,
        ($member_row->current==1)?"current":"not a member",
        $member_row->date_joined,
        $member_row->title,
        $member_row->first_names,
        $member_row->last_names);
        $x = 0;
        foreach($tmpary as $value){
            echo 'tempary[' . $x . '] = "' . $value . '";';
            $x++;
            }
?>
//      tempary=JSON.parse("<?php echo json_encode($tmpary); ?>");
        document.write(tempary[4] +"<br />");       //debug
        console.log(tempary);           //debug
        members.push(tempary);
<?php       }
?>
    document.write(members + "<br />");     //debug
    document.write("Hi Will again<br />");      //debug
    for (mem in members)
        {
        console.log(members.length + " " + mem.length + " " + members[1]);  //debug
        console.log(mem + " " + mem[0] + " " + mem[1] + " " + mem[2] + " " + mem[3] + " " + mem[4]);    //debug

        }
</script>

I've been wrestling with this for several days now and running out of ideas. 我已经为此花了几天的时间来解决这个问题。 Any help would be greatly appreciated. 任何帮助将不胜感激。

I see that you are overwriting your tempary array on each iteration. 我看到您在每次迭代中都覆盖了临时数组。 And so by the time you json_encode, you are left with just the last item. 因此,当您使用json_encode时,仅剩下最后一项。

Try this instead: 尝试以下方法:

global $wpdb;
$query="SELECT * FROM wp_ta_members";
$member_table=$wpdb->get_results($query);
echo "<p>Size of wp_ta_members table is " . count($member_table) . "</p>";      //debug
?>
<script type="text/javascript">
<?php
$members = array();
foreach ($member_table as $member_row){
    $member = array(
        $member_row->member_id,
        ($member_row->current==1)?"current":"not a member",
        $member_row->date_joined,
        $member_row->title,
        $member_row->first_names,
        $member_row->last_names
    );
    $members[] = $member;
}
?>
var members = <?php echo json_encode($members) ?>;
</script>
<?php   }
?>   

I discovered where my problem lay. 我发现了问题所在。 Especially killneel who came up with a really elegant solution to the 2D array problem. 特别是killneel ,他提出了一种非常优雅的解决二维阵列问题的方法。 It turned out that the crux of the problem was in the way I was accessing the array. 事实证明,问题的症结在于我访问阵列的方式。 Just for reference NEVER user a for..in loop to process an array! 仅供参考,切勿使用for..in循环来处理数组! It is so much better to use: 使用起来更好:

var len = arr.length;
for (var i=0; i<len; i++) {
    console.log(arr[0];     // or whatever you want to do with the array element
    }

Use a foreach loop and write out the JS code on each iteration after declaring the JS array: 在声明JS数组之后,使用foreach循环并在每次迭代中写出JS代码:

<script>

var js_array = new Array();

<?php

    $x = 0;

    foreach($item as $key => $value){

        echo 'js_array[$x] = "' . $value . '";';

        $x++;
    }

?>

</script>

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

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