简体   繁体   中英

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:

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".

If I output tempary itself, I get a string of all the elements separated by commas.

What I am I missing? I want tempary to be a proper JavaScript array.

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).

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. Joe Soap is the last member in the list. Why 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 !! The remaining elements of mem are "undefined".

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.

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. 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! 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:

<script>

var js_array = new Array();

<?php

    $x = 0;

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

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

        $x++;
    }

?>

</script>

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