Matching array elements to get an array element at another index
- by bccarlso
I have a PHP array that I'm using to generate an HTML form. The PHP array is this:
<?php
$vdb = array (
array( "Alabama", 275),
array( "Alaska", 197),
array( "Arizona", 3322));
?>
The PHP to generate the HTML form is below. I need to have the value be the name of the state, because there is some AJAX I'm using to display which states a user has chosen.
<?php
echo "<table border='1'><thead><tr><th></th><th>State</th><th>Contacts</th><th>Email</th></tr></thead>";
for ($row = 0; $row < 42; $row++) {
echo "<tr><td class='input_button'><input type='checkbox' name='vdb[]' value='".$vdb[$row][0]."' title='".$vdb[$row][1]."' /></td>";
echo "<td>".$vdb[$row][0]."</td>";
echo "<td>".$vdb[$row][1]."</td>";
}
echo "</table>";
?>
What I'm trying to do is, on submission of the form, with the states the user selected, loop through the PHP array and total the numbers from the selected states. So if I checked Alabama and Alaska, I'd want to add 275 + 197.
This is what I thought would have worked, but it's not:
<?php
$vendors = array();
if (isset($_POST["vdb"])) {
$vendors = $_POST["vdb"];
}
$ven_i = 0;
$ven_j = 0;
$ven_total = 0;
foreach ($vendors as $value) {
foreach ($vdb as $vdb_value) {
if ($vendors[$ven_i] == $vdb[$ven_j][0]) {
$ven_total += $vdb[$ven_j][1];
}
$ven_j++;
}
$ven_i++;
}
?>
and then $ven_total should be the total I'm looking for. However, $ven_total just ends up being the first checkbox selected, and it ignores the rest. I am doing this correctly with the AJAX, displaying the total on the front end, but I don't know how to pass that on to the form submission. I'd rather not using GET and URL variables, because a user could type something into the URL and modify the count. Any idea what I'm doing wrong, or a better way to approach this that I would be able to understand? (Very much a novice programmer.)