$testArray = array(
array(1,2,"file1.png"),
array(1,3,"file2.png"),
array(1,4,"file3.png")
);
print_r (array_keys($testArray, array(1,3, "file2.png"))); // Works
print_r (array_keys($testArray, array(1,3))); // Does not work.
如上面的代码所示,我希望能够在多维数组中快速找到一个数组,但仅指定两个值。
答案 0 :(得分:0)
您可以通过计算交集来测试哪些数组包含值,从而对数组进行过滤,然后获取这些键:
| ClientCase_ID | AssociatedPerson_ID | AssociatedPersonType | AssociatedType_ID |
|---------------|---------------------|----------------------|-------------------|
| 01 | 01 | ResPonsible Party | 16 |
| 02 | 03 | Physician Therapist | 24 |
您可以使用搜索$keys = array_keys(array_filter($testArray,
function($v) {
return count(array_intersect([1,3], $v)) == 2;
}));
变量对其进行扩展:
$s
这将返回包含$s = [1,3];
$keys = array_keys(array_filter($testArray,
function($v) use($s) {
return count(array_intersect($s, $v)) == count($s);
}));
,[1,3]
或什至[3,1]
,顺序无关的任何子数组的键。
要按顺序检查它们:
[3,"file2.png",1]
答案 1 :(得分:0)
执行此操作的一种方法是使用array_map将testArray过滤到相应数量的键,然后使用array_search获取键。
$testArray = array(
array(1,2,"file1.png"),
array(1,3,"file2.png"),
array(1,4,"file3.png")
);
$search = [1,3];
$filtered = array_map(function ($item) use ($search){
return array_slice($item, 0, count($search));
}, $testArray);
$key = array_search($search, $filtered);
if ($key !== false){
print_r($testArray[$key]);
} else {
echo 'not found';
}
答案 2 :(得分:0)
这应该有效:
$needle = [1, 3];
$found = [];
foreach ($testArray as $k => $v) {
if(count(array_intersect_assoc($needle, $v)) == count($needle)) {
$found[] = $v;
}
}
echo '<pre>';
$found ? print_r($found) : print_r('not found');
答案 3 :(得分:0)
<?php
$data = array(
array(1,2,"file1.png"),
array(1,3,"file2.png"),
array(1,4,"file3.png")
);
$partial_matches = null;
foreach($data as $k => $v)
if (array_slice($v, 0, 2) == [1,3])
$partial_matches[] = $k;
var_dump($partial_matches);
输出:
array(1) {
[0]=>
int(1)
}