2

好吧。我有一个这样定义的填充数组:

$subs = array();
for (...) {
    // extracting of variables $knowledgeLevel, $name, $short, $long
    $subs [] = array (
         'knowledgeLevel' => $knowledgeLevel,
         'name' => $name,
         'shortTheory' => $short,
         'longTheory' => $long
    );
}

然后我收到一个值$kl,我想最终从数组$subselement删除knowledgeLevel等于$kl。我试过这样做:

foreach ( $subs as $subject ) {
    if ($subject['knowledgeLevel'] == $kl) {
        unset ($subject);
    }
}

所以

foreach ( $subs as $subject ) {
    if ($subject['knowledgeLevel'] == $kl) {
        unset ($subject['knowledgeLevel']);
        unset ($subject['name']);
        unset ($subject['shortTheory']);
        unset ($subject['longTheory']);
    }
}

但这些似乎不起作用。

4

2 回答 2

3

为了能够直接修改循环内的数组元素,在 $value 之前加上 &。在这种情况下,该值将通过引用分配。

&与_foreach ( $subs as &$subject )

foreach ( $subs as &$subject ) 
    if ( $subject['knowledgeLevel'] == $kl ) 
        unset ($subject);

或者试试这个:

此表单将在每次迭代时将当前元素的键另外分配给 $key 变量。

foreach ( $subs as $key => $subject )
    if ( $subject['knowledgeLevel'] == $kl ) 
        unset( $subs[$key] );
于 2013-05-11T08:33:46.593 回答
0

$subject不是引用$subs它的新变量,并且unset($subject['anything'])您不会从中删除任何内容$subs

使用for循环:

for($i=0;$i<count($subs);$i++) {
   if ($subs[$i]['knowledgeLevel'] == $kl) {
       unset ($subs[$i]);
   }
}
于 2013-05-11T08:36:06.193 回答