fastest way to get parent array key in multidimens

2019-04-09 23:02发布

问题:

what is the best way to get parent array key with multidimensional arrays? for example I have this array:

array(

    [0] => array(0=> sample, 1=>picture, 2=>frame, 3=>google)

    [1] => array(0=> iphone, 1=>orange, 2=>love, 3=>msn)

    [2] => array(0=> joe, 1=>geee, 2=>panda, 3=>yahoo)
)

now I need to search for example google and get the parent array key.. which it should be 0...any ideas? I used for loop for this but I think it will be slow if I have arrays with 700000 rows..

回答1:

If you have an array with 700,000 rows you are almost certainly doing something wrong... I would first recomend thinking about utilizing a different data store: flat file or some type of DB.


foreach($array as $key => $value) {
    if(in_array('google', $value)) return $key
}



回答2:

Arrays with 700,000 rows? How many arrays? 9/10 times problem is that you've got your data set up wrongly.

I'm going to go ahead and assume you're doing a search of some sort. As you can't index an array (in the search meaning of index) then you're probably best putting the data into a database and making the most of column indexing to search fast.

Depending on context, you may alternatively want to think about storing your data in files, one per array, and using file searches to find which file contains your value.