使用一个项目访问2D关联数组的键

时间:2013-02-12 01:33:41

标签: php associative-array

对于“提交”输入项:

name="remove['.$username.']['.$event_id.']" 

if (isset($_POST[remove])) {
    foreach ($_POST[remove] as $username => $event_obj) {
        foreach ($event_obj as $event_id => $obj) {
            delete .... WHERE event_id='$event_id' AND username='$username'");
        }
    }
}

是否有更短的方法来获取具有一个项目的数组中使用的关联键?

1 个答案:

答案 0 :(得分:0)

使用array_keys()一次获取所有event_id值。这也只需要每个用户名一个查询。

if( isset( $_POST['remove'])) {
    foreach( $_POST['remove'] as $username => $event_obj) {
        $event_ids = array_map( 'intval', array_keys( $event_obj));
        $sql = 'DELETE FROM mytable 
                    WHERE event_id IN ( ' . implode( ' OR ', $event_ids) . ' ) 
                        AND username = "' . $username  . '"'; // Sanitize $username
    }
}