douzuo5504 2015-02-02 06:05
浏览 35
已采纳

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

I have a php array with mixed data types (arrays, ints, strings). I want to search the array for a match contained within an array of mixed data types as show below.

my test array

$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"]
    ]
];

If the needle is set to an element and that element is found to exists in actorNoms, I want to echo back the name of the associated actor (actorName). In the below example, I have attempted to find cyclops (actorNoms) return the name of the actor, Michael Pare (actorName) who is associated with him.

My Attempt to find actorNoms and return the actors name

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

My attempt returns fails as it echo's 'nothing found'. How do I echo back the name of the actor Michael Pare when searching for cyclops.

Thank you for any help given. I have tried to format my code correctly for ease of use. I have searched Stack, Google and other sources for several hours now trying to find a solution I can understand. I am not very adept, but I promise I am learning and all help is appreciated.

  • 写回答

3条回答 默认 最新

  • duan0403788996 2015-02-02 06:18
    关注

    Instead of using

    if(in_array($needle, $haystack)) { 
        echo $haystack['actorNoms'] . '<br />' ;
    }
    

    try this:

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

    what you did was search the $haystack which is the main array for the actors.

    in_array doesn't search nested arrays automatically for multidimensional arrays, hence you need to specify the area in which you would search: in_array($haystack['actorNoms'])

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里