Comment vérifier si une certaine partie du tableau existe dans un autre tableau?
-
10-07-2019 - |
Question
J'ai deux tableaux associatifs et je veux vérifier si
$array1["foo"]["bar"]["baz"] exists in $array2["foo"]["bar"]["baz"]
Les valeurs importent peu, juste le "chemin". array_ intersect_ assoc fait-il ce dont j'ai besoin? < br> Si non, comment puis-je en écrire un moi-même?
La solution
Essayez ceci:
<?php
function array_path_exists(&$array, $path, $separator = '/')
{
$a =& $array;
$paths = explode($separator, $path);
$i = 0;
foreach ($paths as $p) {
if (isset($a[$p])) {
if ($i == count($paths) - 1) {
return TRUE;
}
elseif(is_array($a[$p])) {
$a =& $a[$p];
}
else {
return FALSE;
}
}
else {
return FALSE;
}
$i++;
}
}
// Test
$test = array(
'foo' => array(
'bar' => array(
'baz' => 1
)
),
'bar' => 1
);
echo array_path_exists($test, 'foo/bar/baz');
?>
Autres conseils
Si vous avez seulement besoin de vérifier si les clés existent, vous pouvez utiliser une simple instruction if.
<?php
if (isset($array1["foo"]["bar"]["baz"]) && isset($array2["foo"]["bar"]["baz"]
)) { // existe }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow