嵌套数组中的 Search_array [英] Search_array in nested arrays

查看:27
本文介绍了嵌套数组中的 Search_array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有嵌套数组的数组,我试图使用 *search_array* 函数来筛选数组并将它们的键还给我.它一直没有工作.代码如下:

I've got an array with nested arrays, and I was trying to use the *search_array* function to sift through the array and give me back their keys. It hasn't been working. Here's the code:

<?php 
$array = array(
   'cat1' => array(1,2,3),
   'cat2' => array(4,5,6),
   'cat3' => array(7,8,9),
);

foreach($array as $cat){
   if(is_array($cat)
      echo array_search(5,$cat); //want it to return 'cat2'
   else
      echo array_search(5,$array);
}

谢谢!

推荐答案

如果你总是有一个二维数组,那么就这么简单:

If you always have a two-dimensional array, then it is as easy as:

function find($needle, $haystack) {
    foreach($haystack as $key=>$value){
       if(is_array($value) && array_search($needle, $value) !== false) {
          return $key;
       }
    }
    return false;
}

$cat = find(5, $array);

这篇关于嵌套数组中的 Search_array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆