我有一个包含混合数据类型(数组,整数,字符串)的php数组。我想在数组中搜索包含在混合数据类型数组中的匹配项,如下所示。
我的测试数组
$arrActors =[0 => [
'actorName' => "heath ledger",
'actorAlias' => [],
'actorGender' => 1,
'actorNoms' => ["angel", "john constantine"]
],
1 => [
'actorName' => "Michael pare",
'actorAlias' => ["mikey", "that guy"],
'actorGender' => 1,
'actorNoms' => ["cyclops", "slim", "eric the red"]
]
];
如果针被设置为元素并且发现该元素存在于actorNoms中,我想回显关联的actor(actorName)的名称。在下面的例子中,我试图找到独眼巨人(actorNoms)返回与他相关联的演员,Michael Pare(actorName)的名字。
我尝试找到actorNoms并返回演员姓名
$needle = 'cyclops';
foreach($arrActors as $haystack)
{
if(in_array($needle, $haystack)) {
echo $haystack['actorNoms'] . '<br />' ;
}else{
echo 'nothing found<br />';//echo something so i know it ran
}
}
我的尝试返回失败,因为它回显'找不到任何东西'。在搜索独眼巨人时,如何回显演员Michael Pare的名字。
感谢您提供任何帮助。我试图正确格式化我的代码以方便使用。我已经搜索了Stack,Google和其他来源几个小时,现在试图找到一个我能理解的解决方案。我不是很擅长,但我保证我正在学习,所有的帮助都表示赞赏。
答案 0 :(得分:1)
而不是使用
if(in_array($needle, $haystack)) {
echo $haystack['actorNoms'] . '<br />' ;
}
试试这个:
if(in_array($needle, $haystack['actorNoms'])) {
echo $haystack['actorName'] . '<br />' ;
}
你所做的是搜索$haystack
这是演员的主阵列。
in_array
不会自动搜索多维数组的嵌套数组,因此您需要指定要搜索的区域:in_array($haystack['actorNoms'])
答案 1 :(得分:1)
$needle = 'cyclops';
foreach($arrActors as $haystack)
{
if(in_array($needle, $haystack['actorNoms'])) {
echo $haystack['actorName'] . '<br />' ;
}
}
in_array,仅适用于一个级别的数组。因此,每当它通过第一级数组时,其中作为“演员”和“演员阵容”。是firstlevel数组下的子数组。
答案 2 :(得分:1)
尝试此操作,使用此索引为您提供父索引,您将获得数据
$arrActors = array( array(
'actorName' => "heath ledger",
'actorAlias' => array(),
'actorGender' => 1,
'actorNoms' => array("angel", "john constantine")
),array(
'actorName' => "Michael pare",
'actorAlias' => array("mikey", "that guy"),
'actorGender' => 1,
'actorNoms' => array("cyclops", "slim", "eric the red")
)
);
print_r( getParent_id("cyclops",$arrActors));
function getParent_id($child, $stack) {
foreach ($stack as $k => $v) {
if (is_array($v)) {
// If the current element of the array is an array, recurse it and capture the return
$return = getParent_id($child, $v);
// If the return is an array, stack it and return it
if (is_array($return)) {
return array($k => $return);
}
} else {
// Since we are not on an array, compare directly
if (preg_match("/$child/",$v)) {
// And if we match, stack it and return it
return array($k => $child);
}
}
}
// Return false since there was nothing found
return false;
}