我正在寻找一种通过键/值搜索来删除子阵列的方法,使用如下方法:array_remove($ array,$ searchingKey,$ searchingValue):
示例:
array(
0 => array
(
"userId" => 123,
"address" => "brian@gmail.com",
"smtp" => 1
),
1 => array
(
"userId" => 124,
"address" => "helen@gmail.com",
"smtp" => 1
),
2 => array
(
"userId" => 125,
"address" => "albert@gmail.com",
"smtp" => 2
)
)
如果我正在搜索此地址:helen@gmail.com with array_remove($ myarray," address"," helen@gmail.com");
期望的结果:
array(
0 => array
(
"userId" => 123,
"address" => "brian@gmail.com",
"smtp" => 1
),
1 => array
(
"userId" => 125,
"address" => "albert@gmail.com",
"smtp" => 2
)
)
或像这样搜索smtp键 array_remove($ myarray中," SMTP",1);
预期结果:
array(
0 => array
(
"userId" => 125,
"address" => "albert@gmail.com",
"smtp" => 2
)
)
我尝试使用walk_array_recursive()这样做,但我失败了。
答案 0 :(得分:0)
function remove($arr, $key, $val){
$foundKey = '';
foreach($arr as $k=>$a){
if($a[$key] == $val){
$foundKey = $k;
}
}
return $foundKey;
}
$foundkey = remove($aa, 'address', 'helen@gmail.com');
现在取消设置数组
if(isset($aa[$foundkey])){
unset($aa[$foundkey]);
}
echo "<pre>"; print_r($aa);
或者如果你想从函数中返回最终数组,请在那里取消设置并返回数组,而不是像$foundKey
那样返回
function remove($arr, $key, $val){
foreach($arr as $k=>$a){
if($a[$key] == $val){
$foundKey = $k;
}
}
if(isset($arr[$foundkey])){
unset($arr[$foundkey]);
}
return $arr;
}
答案 1 :(得分:0)
您可以尝试使用此自定义递归函数:
<?php
array_remove($array, "address", "helen@gmail.com");
var_dump($array);
array_remove($array, "smtp", 2);
var_dump($array);
function array_remove(array &$haystack, $needleKey, $needleValue, array &$parent = array(), $previousKey = null) {
foreach($haystack as $key => $value) {
if(is_array($value)) {
array_remove($value, $needleKey, $needleValue, $haystack, $key);
}elseif($key === $needleKey && $value === $needleValue) {
unset($parent[$previousKey]);
}
}
}