Sorry i could not find a proper title to this question. I have generated the following using a for loop and I have concatenated the names of the submits开发者_运维知识库 buttons using the pattern below: submit_edit_category_1 submit_edit_category_2 submit_edit_category_3
echo "<input type='submit' value = 'Edit' name='submit_edit_category_" .
$obj_categories_admin->categories[$i]['category_id'] . "'/>";
I want to loop through these values so that I can the button action whichis edit_category and the category id which is 1,2 or 3. I want to so something like:
if(isset($_POST) == 'edit_category'))
{
//code here
}
Someone suggested me to do it this way:
name="submit[which_action][which_category]"
a1 = $_POST['submit'];
$which_action = reset(array_keys($a1));
$which_category = reset(array_keys($a1[$which_action]));
This does not seem to work..Can anyone give me a different way to do it? Thanks!
UPD: Please, use Mike's advice. It's much better to have more structured data in POST.
foreach($_POST as $key => $val) {
if(strpos($key, 'submit_edit_category_') === 0 ) {
print $key.' => '.$val.'\r\n';
print substr($key, 21 /* or 22... or 23... try yourself */ );
}
}
here what I'd do:
for the actual form, I'd use array keys to communicate action and relevant id info.
$cat_id = $obj_categories_admin->categories[$i]['category_id'];
echo "<input type='submit' value = 'Edit' name='submit[edit_category][" . $cat_id . "]'/>";
then when posted, I can do:
<?php
list($action, $action_params) = each($_POST['submit']);
list($cat_id, $button_label) = each($action_params);
print_r($_POST['submit']); // prints array('edit_category' => array('1' => 'Edit'))
echo($action); //prints "edit_category"
print_r($action_params); //prints array('1' => 'Edit')
echo($cat_id); //prints "1"
echo($button_label); //prints "Edit"
edit: for more info on each(), go here: http://us2.php.net/each . I've personally always felt that 's lack of differentation between the button label and the it's value to be frustrating. Using an array key to stuff info into the button has always been my favorite hack.
You can try this:
foreach ($_POST AS $key=>$value) {
if (strpos($key, 'submit_edit_category_') !== false) {
$catID = (int)str_replace('submit_edit_category_', '', $key);
echo 'Category ID: ' . $catID . '<br />';
}
}
I'd change the way you build the name to this:
submit__edit_category__1
Then, try this:
function filter_by_submit($var)
{
return stripos($var, "submit") !== false ? true : false;
}
$submits = array_filter(array_keys($_POST), "filter_by_submit");
foreach ($submits as $sub)
{
if ($_POST[$sub] == "Edit")
{
list($submit, $action, $id) = explode("__", $sub);
break;
}
}
$submit
will hold the string "submit"
. $action
will hold "edit_category"
and $id
will hold the id of the pressed button. The pressed button is determined by matching its value to the tag's value (i.e., when submit__edit_category__1 is pressed, the value "Edit"
is POSTed).
精彩评论