php - 如何使用特定键在多维数组中查找特定值
问题描述
我有一个看起来像这样的数组
$myArray = Array
(
[Standardbox] => Array
(
[details] => Array
(
[name] => Standardbox
)
[resources] => Array
(
[0] => Array
(
[resourceId] => 1
[resourceName] => Knife
[amount] => 1
[unit] => 2
)
[1] => Array
(
[resourceId] => 2
[resourceName] => Fork
[amount] => 1
[unit] => 2
)
)
)
)
我想检查数组中是否value
存在(刀)的 1
。key
resourceId
我在 stackoverflow 找到了一些函数,但没有什么真正适合我的目的:
这个看起来很有希望,但我认为它不认为数组是多维的:
function multi_key_in_array($needle, $haystack, $key)
{
foreach ($haystack as $h)
{
if (array_key_exists($key, $h) && $h[$key]==$needle)
{
return true;
}
}
return false;
}
然后打电话
if(multi_key_in_array(1, $myArray, "resourceId"))
{
// It is present in the array
}
非常感谢任何帮助!
解决方案
<?php
function multi_key_in_array($needle, $haystack, $key)
{
foreach ($haystack as $h)
{
if (array_key_exists($key, $h) && $h[$key]==$needle)
{
return true;
}
}
return false;
}
$myArray = Array
(
'Standardbox' => Array
(
'details' => Array
(
'name' => 'Standardbox'
),
'resources' => Array
(
0 => Array
(
'resourceId' => 1,
'resourceName' => 'Knife',
'amount' => 1,
'unit' => 2
),
1 => Array
(
'resourceId' => 2,
'resourceName' => 'Fork',
'amount' => 1,
'unit' => 2
)
)
)
);
if(multi_key_in_array(1, $myArray['Standardbox']['resources'], "resourceId"))
{
echo 'true';
} else {
echo 'false';
}
> Blockquote
推荐阅读
- c# - 比较多个列表时删除相同的值
- css - 有没有办法让一个 flex/grid 孩子(三个以上)居中并且宽度不同?
- r - R 和 Tibco 的编码问题
- angular - 在 Angular *ngFor 中使用偶数和奇数
- c# - 具有动态参数的 UnityEvent 不再在 Unity 检查器中显示
- javascript - 从多个数据 JSON 数组写入响应
- java - 不能使用 CompositeItemWriter:ItemWriter 不是 ItemStream
- wso2 - 在丰富的调解器中处理 xml 值
- c# - 从 Outlook 电子邮件执行 C# 过程
- pdf - 以编程方式将 .PBIX 文件导出为 .PDF