[英]Search a multi-dimensional array for certain values
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: 我想搜索一个值,它们返回一个数组,该数组包含匹配数组中的所有键,并且在搜索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. 我知道我正在尝试将数组视为数据库,但是在这种情况下,程序结束后不需要存储动态数据。
Any advice? 有什么建议吗?
Loop through the array: 遍历数组:
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');
you must iterate array like: 您必须像这样迭代数组:
foreach ($array as $i => $values) {
print "$i {\n";
foreach ($values as $key => $value) {
print " $key => $value\n";
}
print "}\n";
}
and then check for 'type' key value.... then record which is matched must copy it to new array... 然后检查'type'键值...。然后匹配的记录必须将其复制到新数组中...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.