我有一个具有混合数据类型(数组、ints、字符串)的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中,则我希望回显关联参与者(actorName)的名称。在下面的示例中,我试图找到独眼巨人(actorNoms)返回与他关联的演员Michael (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
}
}我的尝试失败了,因为它呼应了“什么都找不到”。当我搜索独眼巨人的时候,我该如何回复演员迈克尔·帕尔的名字呢?
谢谢你的帮助。为了便于使用,我试图正确格式化我的代码。我已经搜索了Stack,Google和其他来源好几个小时,试图找到一个我能理解的解决方案。我不是很在行,但我保证我在学习,所有的帮助都很感激。
发布于 2015-02-02 06:18:06
而不是使用
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'])
发布于 2015-02-02 06:18:22
$needle = 'cyclops';
foreach($arrActors as $haystack)
{
if(in_array($needle, $haystack['actorNoms'])) {
echo $haystack['actorName'] . '<br />' ;
}
}数组,只适用于一个级别数组。因此,每次它经过第一级数组,其中as 'actorNoms‘是第一级数组下的子数组。
发布于 2015-02-02 06:20:47
尝试这个,这给你的父索引使用这个索引,你会得到数据
$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;
}https://stackoverflow.com/questions/28271959
复制相似问题