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.
console.log(tempary)
? What's its results? Besides you wrote$tmpary
as a PHP variable. Maybe it's a typo. – kernel 23 hours ago