搜索具有混合数据类型的多维数组,回显结果


search multidimensional array with mixed data types, echo back result

我有一个混合数据类型(数组,整数,字符串)的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 Pare(actorName)的名字。

我尝试查找演员名词并返回演员姓名

$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和其他来源几个小时,试图找到一个我可以理解的解决方案。我不是很熟练,但我保证我正在学习,感谢所有的帮助。

而不是使用

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'])

$needle = 'cyclops';
foreach($arrActors as $haystack) 
{   
    if(in_array($needle, $haystack['actorNoms'])) { 
        echo $haystack['actorName'] . '<br />' ;
    }
}

in_array,仅适用于一级数组。所以每次它通过第一级数组时,其中"actorNoms"是一级数组下的子数组。

试试这个给你父索引 使用此索引您将获得数据

$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;
    }