0

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. e.g.

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 e.g. 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.

5
  • I would suggest that you put the array values in html elements then call these elements in JS and store it in an array. Commented Oct 24, 2014 at 10:35
  • 1
    Did you try to console.log(tempary)? What's its results? Besides you wrote $tmpary as a PHP variable. Maybe it's a typo. Commented Oct 24, 2014 at 10:40
  • JSON.parse()? Commented Oct 24, 2014 at 10:42
  • 'tempary = JSON.parse("<?php echo json_encode($var); ?>");' then console.log(tempary); and see what is the structure if your object in developer mode. Commented Oct 24, 2014 at 10:44
  • The result of console.log(tempary) is: ["78", "current", "2014-01-01", "Mr", "Fred", "Bloggs"] . That is to say a comma separated list as I said. Yes - $tmpary is a PHP variable. This is the array I want to copy to a JavaScript array. I'll try the JSON.parse idea. Commented Oct 24, 2014 at 22:49

3 Answers 3

1

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   }
?>   
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help. You are right that I am using overwriting tempary on each iteration, but I am also using members.push() to add the contents of tempary each time to members so that I can reuse tempary. I will try your solution however.
Thanks killneel. However, I want to end up with an array of arrays. That is members[] is an array of member[] arrays. The above doesn't seem to do it.
My answer actually builds up a multidimensional array (an array of member arrays) in php and then echo out the json string of that php array. You can see that on each iteration of the foreach loop, $member is initialised and populated with values from the table row. This array is then pushed onto members array so that in the end, members would be a numerically index array with each element in it consisting of an array.
Finally understood what you meant by overwriting tempary. It would appear that pushing it to an element of an outer array must only be as a pointer to the original array, so that if that original is overwritten, the data in the outer (2D) array is also reflected. This is why I was getting umpteem copies (or so it appeared) of the final array. Thanks for pointing this out.
1

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
    }

1 Comment

you can upvote after you gain 15 rep
0

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>

2 Comments

<?php $x = 0; foreach($member_row as $value){ echo 'tempary[' . $x . '] = "' . $value . '";'; $x++; } ?>
I had to modify your code to: <?php $x = 0; foreach($member_row as $value){ echo 'tempary[' . $x . '] = "' . $value . '";'; $x++; } ?> But it still doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.