我正在尝试构建一个允许搜索多维数组的函数,其中每个子数组都匹配多个条件。我遇到一个奇怪的行为,无法弄清为什么会发生。
以下是导致问题的一般逻辑。我在PHP 7.4上运行它的价值。最终的键数组($keys2
)应该与第一个键数组($keys
)匹配,但是它将失去与期望索引的关联。看来PHP忽略了我给定的int索引,而是在最后的array_keys()
调用上使用了看不见的0索引。
$array = [ ['one' => 'aa', 'two' => 'qq'], ['one' => 'bb', 'two' => 'qq'], ['one' => 'aa', 'two' => 'qq'], ['one' => 'bb', 'two' => 'qq'], ['one' => 'aa', 'two' => 'qq'], ]; $keys = array_keys(array_column($array, 'one'), 'aa'); $array2 = array_filter($array, static function($key) use ($keys) { return in_array($key, $keys, true); }, ARRAY_FILTER_USE_KEY); $keys2 = array_keys(array_column($array2, 'two'), 'qq'); echo '<pre>'; var_dump($array, $keys, $array2, $keys2); echo '</pre>';
以上输出:
/var/www/test.php:
array (size=5)
0 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
1 =>
array (size=2)
'one' => string 'bb' (length=2)
'two' => string 'qq' (length=2)
2 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
3 =>
array (size=2)
'one' => string 'bb' (length=2)
'two' => string 'qq' (length=2)
4 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
/var/www/test.php:
array (size=3)
0 => int 0
1 => int 2
2 => int 4
/var/www/test.php:27:
array (size=3)
0 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
2 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
4 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
/var/www/test.php:
array (size=3)
0 => int 0
1 => int 1
2 => int 2
我正在尝试构建一个允许搜索多维数组的函数,其中每个子数组都匹配多个条件。我遇到一个奇怪的行为,无法弄清为什么...
<?php
$array = [
['one' => 'aa', 'two' => 'qq'],
['one' => 'bb', 'two' => 'qq'],
['one' => 'aa', 'two' => 'qq'],
['one' => 'bb', 'two' => 'qq'],
['one' => 'aa', 'two' => 'qq'],
];
$keys = array_keys(array_column($array, 'one'), 'aa');
$array2 = array_filter($array, static function($key) use ($keys) {
return in_array($key, $keys, true);
}, ARRAY_FILTER_USE_KEY);
$keys2 = array_keys(array_combine(array_keys($array2), array_column($array2, 'two')), 'qq', true);
echo '<pre>';
var_dump($array, $keys, $array2, $keys2);
echo '</pre>';