gpt4 book ai didi

php - 从php中的数组中删除一个元素

转载 作者:行者123 更新时间:2023-12-04 04:58:11 24 4
gpt4 key购买 nike

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

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

然后我收到一个值 $kl ,我想最终从数组中删除 $subs elementknowledgeLevel等于 $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']);
}
}

但这些似乎不起作用。

最佳答案

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.



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

或者试试这个:

This form will additionally assign the current element's key to the $key variable on each iteration.


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

关于php - 从php中的数组中删除一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com