搜索特定值的多维数组 [英] Search a multi-dimensional array for certain values

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

问题描述

我有以下格式的多维数组:

I have a multi-dimensional array in the following format:

[0] = (
    'id' => '1',
    'type' => 'fish', 
    'owner' => 'bob',
)

[1] = (
    'id' => '2',
    'type' => 'cat', 
    'owner' => 'mary',
)

[2] = (
    'id' => '3',
    'type' => 'dog', 
    'owner' => 'larry',
)

[3] = (
    'id' => '2',
    'type' => 'cat', 
    'owner' => 'fred',
)

我想搜索的价值,他们返回一个包含匹配阵列的所有按键,看起来像这样对类型搜索=猫数组:

I would like to search for a value, and they return an array that contains all keys from matching arrays and looks like this on a search for type=cat:

[0] = (
    'id' => '2',
    'type' => 'cat', 
    'owner' => 'mary',
)

[1] = (
    'id' => '2',
    'type' => 'cat', 
    'owner' => 'fred',
)

我知道我试图治疗阵列作为数据库,但在这种情况下,它不需要一旦程序结束要存储动态数据。

I know I'm trying to treat the array as a database, but in this case it's dynamic data that doesn't need to be stored once the program ends.

任何意见?

推荐答案

遍历数组:

function loopAndFind($array, $index, $search){
         $returnArray = array();
         foreach($array as $k=>$v){
               if($v[$index] == $search){   
                    $returnArray[] = $v;
               }
         }
         return $returnArray;
}

//use it:
$newArray = loopAndFind($oldArray, 'type', 'cat');

这篇关于搜索特定值的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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