开发者

Search a value in two dimension arrays

开发者 https://www.devze.com 2023-02-26 04:51 出处:网络
I have many arrays like this: Array ( [1] => Array ( [Field] => column1 [Type] => varchar(50) [PrimaryKey] => PRI )

I have many arrays like this:

Array ( 
  [1] => Array ( [Field] => column1 [Type] => varchar(50) [PrimaryKey] => PRI ) 
  [2] => Array ( [Field] => column2 [Type] => varchar(50) [PrimaryKey] => ) 
  [3] => Array ( [Field] => column3 [Type] => timestamp [PrimaryKey] => ) 
  [4] => Array ( [Field] => column4 [Type] => varchar(50) [PrimaryKey] => ) 
  [5] => Array ( [Field] => column5 [Type] => varchar(50) [PrimaryKey] => ) 
  [6] => Array ( [Field] => column6 [Type] => varchar(50) [PrimaryKey] => ) 
  [7] => Arr开发者_Python百科ay ( [Field] => column7 [Type] => varchar(50) [PrimaryKey] => ) 
  [8] => Array ( [Field] => column8 [Type] => timestamp [PrimaryKey] => ) 
  [9] => Array ( [Field] => column9 [Type] => varchar(50) [PrimaryKey] => ) 
) 

I want to know if any array contains a sub-array with Field=column1. What is the shortest way to check this in each array.

When I use loops and nested loops, it takes so much time and finally shows a memory exhausted error.

Thanks.


foreach($myArr as $arrays){
  if($arrays['Field']=='column1'){
   echo "Found";
   break;
  }
}


foreach($outerArray as $k => $v) {
    if($v['FieldName'] == "Value") {
        $found = true;
        break;
    }
}


foreach ($array as $key => & $sub_array) {
  if ($sub_array['Field'] == 'column1') {
    //found it!
  }
}

Doesn't require a lot of memory and fast enough.

Or i don't get it.


You can use http://www.php.net/manual/de/function.array-walk-recursive.php or a combination of one loop and http://www.php.net/manual/de/function.array-key-exists.php - that's up to you. But you'll have to iterate in one way or another (or a php function that you call will do that for you).

If you have a large array, consider splitting it up into batches so that your memory doesn't get overloaded.

0

精彩评论

暂无评论...
验证码 换一张
取 消