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条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站