use*_*810 5 php arrays multidimensional-array
我正在努力使用适当的逻辑来比较以下数组:
$a = [
"ip" => [
"1.2.3.4",
"4.3.2.1",
],
"domain" => [
"example.com",
"another.domain",
],
];
$b = [
[
"id"=> 136589,
"metaname" => "ip",
"metavalue" => "1.2.3.4",
],
[
"id"=> 136590,
"metaname" => "domain",
"metavalue" => "example.com",
],
];
Run Code Online (Sandbox Code Playgroud)
我需要循环$a查找不存在的key('ip')值('1.2.3.4')组合$b.在数组中$a,我需要捕获ip '4.3.2.1'和域'another.domain'
$b有不同键的匹配值是可能的吗?
一个很好的例子就是'ip'地址.可能与IP相关的元名值是'ip','ip.dst'和'ip.src'.返回示例数据 - 即使'ip'匹配,如果metaname不匹配,也应该跳过它.
foreach ($a as $metaName => $metaValues)
{
foreach ($metaValues as $metaValue)
{
foreach ($b as $row)
{
if (in_array($metaName, $row) && in_array($metaValue, $row))
{
# this pair exists, move on to next $metaName-$metaValue pair
break;
}
# this is where i am now, making small progress
# more trial and error going on
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的示例代码中,评论是我需要帮助的地方.我已经尝试了不同的检查和循环的各种迭代来捕获适当的数据无济于事......
in_array($metaValue, $row)array_keys($row, $metaValue) 结合各种if声明等等,但这无济于事.
如果我的描述未能清楚,则下表可能会有所帮助.
+ A ---------------------+----+ B ------------------+ Comment ------------------------+
| ip, 1.2.3.4 | == | ip, 1.2.3.4 | Skip, no more checks |
+------------------------+----+---------------------+---------------------------------+
| ip, 4.3.2.1 | != | ip, 1.2.3.4 | Keep checking |
| | != | domain, example.com | No more B to compare, I want A! |
+------------------------+----+---------------------+---------------------------------+
| domain, example.com | != | ip, 1.2.3.4 | Keep checking |
| | == | domain, example.com | Skip, no more checks |
+------------------------+----+---------------------+---------------------------------+
| domain, another.domain | != | ip, 1.2.3.4 | Keep checking |
| | != | domain, example.com | No more B to compare, I want A! |
+------------------------+----+---------------------+---------------------------------+
Run Code Online (Sandbox Code Playgroud)
只需稍加修改并使用参考,您就已经非常接近了。但要小心第一个 foreach,第一个参数是 a $metaname,但第二个参数还不是$metavalue,您需要第二个 foreach 来循环它们:
foreach ($a as $metaname => &$group) { // & is present to unset the original array
foreach ($group as $i => $metavalue) { // here you get the distinct metavalues
foreach ($b as $row) {
if (!($row['metaname'] === $metaname)) {
continue;
}
if ($row['metavalue'] === $metavalue) {
unset($group[$i]);
}
}
}
}
var_dump($a);
Run Code Online (Sandbox Code Playgroud)
之后var_dump()的一个$a
array(2) {
["ip"]=>
array(1) {
[1]=>
string(7) "4.3.2.1"
}
["domain"]=>
&array(1) {
[1]=>
string(14) "another.domain"
}
}
Run Code Online (Sandbox Code Playgroud)
$a第一个 foreach() 将访问数组的不同值,而$metavalue实际上是包含这些元值的数组。