我试图在多维数组中搜索和删除多个值。
我试图将它与multiDim Search混合使用。
我通过引用传递数组> in_words(10)
=> "zeroone"
。
这可能应该在&$haystack
循环中进行,但是现在它会循环进行。
但没有任何反应
do while
预期结果
$b = array(0 => array("patient" => 123, "condition" => "abc"),
1 => array("patient" => 987, "condition" => "xyz"),
2 => array("patient" => 123, "condition" => "zzz"));
function in_array_r($needle, &$haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
unset($haystack["patient"]);
return true;
}
}
return false;
}
echo in_array_r(123, $b) ? 'found' : 'not found';
Print_r($b);
答案 0 :(得分:1)
由于您没有尝试更改数组中的值,因此无需通过引用传递。但是你走在正确的轨道上!这是一个有效的例子:
$patients = array(0 => array("patient" => 123, "condition" => "abc"),
1 => array("patient" => 987, "condition" => "xyz"),
2 => array("patient" => 123, "condition" => "zzz"));
function remove_patient($patients, $number) {
foreach ($patients as $key => $patient) {
if ($patient['patient'] == $number) {
unset($patients[$key]);
}
}
return $patients;
}
示例结果:
var_dump(remove_patient($patients, 123));
array(1) {
[1]=>
array(2) {
["patient"]=>
int(987)
["condition"]=>
string(3) "xyz"
}
}
答案 1 :(得分:1)
function in_array_r($needle, &$haystack, &$count = 0)
{
foreach($haystack as $index => $data)
{
if(is_array($data))
{
foreach($data as $key => $value)
{
if(is_array($value))
in_array_r($needle, $value, $count);
else
{
if($value === $needle)
{
unset($haystack[$key]);
$count++;
}
}
}
}
}
return $count > 0;
}
$count = 0;
<强> 123 强>:
echo (in_array_r(123, $b, $count) ? "found (".$count ." times)" : "not found") . "\n";
输出:
found (2 times)
<强> 1123 强>:
echo (in_array_r(1123, $b, $count) ? "found (".$count ." times)" : "not found") . "\n";
输出:
not found