我正在尝试从数组中删除键。
这是我从print_r($ cats);
打印得到的Array
(
[0] => <a href="/website/index.php/Category:All" title="Category:All">All</a> > <a href="/website/index.php/Category:Computer_errors" title="Category:Computer errors">Computer errors</a> > <a href="/website/index.php/Category:HTTP_status_codes" title="Category:HTTP status codes">HTTP status codes</a> > <a href="/website/index.php/Category:Internet_terminology" title="Category:Internet terminology">Internet terminology</a>
[1] =>
<a href="/website/index.php/Category:Main" title="Category:Main">Main</a>
)
我正在尝试使用它从数组中删除“Main”类别
function array_cleanup( $array, $todelete )
{
foreach( $array as $key )
{
if ( in_array( $key[ 'Main' ], $todelete ) )
unset( $array[ $key ] );
}
return $array;
}
$newarray = array_cleanup( $cats, array('Main') );
仅供参考我是PHP的新手...显然我看到我犯了错误,但我已经尝试了很多东西而且他们似乎没有工作
答案 0 :(得分:10)
Main不是数组元素,它是数组元素的一部分
function array_cleanup( $array, $todelete )
{
$cloneArray = $array;
foreach( $cloneArray as $key => $value )
{
if (strpos($value, $todelete ) !== false)
unset( $array[ $key ] ); //$array[$key] = str_replace($toDelete, $replaceWith, $value) ; // add one more argument $replaceWith to function
}
return $array;
}
编辑:
with array
function array_cleanup( $array, $todelete )
{
foreach($todelete as $del){
$cloneArray = $array;
foreach( $cloneArray as $key => $value )
{
if (strpos($value, $del ) !== false)
unset( $array[ $key ] ); //$array[$key] = str_replace($toDelete, $replaceWith, $value) ; // add one more argument $replaceWith to function
}
}
return $array;
}
$newarray = array_cleanup( $cats, array('Category:Main') );
答案 1 :(得分:2)
需要注意的是,虽然接受的答案有效,但有一个内置的PHP函数可以处理这个名为array_filter的函数。对于这个特殊的例子,它就像是:
public function arrayRemoveMain($var){
if ( strpos( $var, "Category:Main" ) !== false ) { return false; }
return true;
}
$newarray = array_filter( $cats, "arrayRemoveMain" );
显然有很多方法可以做到这一点,并且接受的答案很可能是最理想的情况,特别是如果有大量的$ todelete选项。使用内置的array_filter,我不知道如何传递$ todelete等附加参数,因此必须为每个选项创建一个新函数。
答案 2 :(得分:0)
这很容易。
$times = ['08:00' => '08:00','09:00' => '09:00','10:00' => '10:00'];
$timesReserved = ['08:00'];
$times = (function() use ($times, $timesReserved) {
foreach($timesReserved as $time){
unset($times[$time]);
}
return $times;
})();
答案 3 :(得分:0)
问题是&#34;如何删除特定密钥&#34; ..如果您正在寻找消除包含特定字符串的密钥,那么这是数组过滤器的答案例如,如果我们想要消除包含&#34; alt _&#34;
的任何内容$arr = array(
"alt_1"=>"val",
"alt_2" => "val",
"good key" => "val"
);
function remove_alt($k) {
if(strpos($k, "alt_") !== false) {
# return false if there's an "alt_" (won't pass array_filter)
return false;
} else {
# all good, return true (let it pass array_filter)
return true;
}
}
$new = array_filter($arr,"remove_alt",ARRAY_FILTER_USE_KEY);
# ^ this tells the script to enable the usage of array keys!
这将返回
数组(&#34;&#34;好键&#34; =&gt;&#34; val&#34;);