Search inside arrays, count, find duplicates, compare [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
开发者_运维问答 Improve this questionSeveral HOW TO questions about simple and multidimensional arrays:
1) How to search in simple and multi arrays?
2) How to count number of search results?
3) How to catch duplicates inside:
3.1 multidimensional array?
3.2 simple array?
3.3 in array's search results?
3.4 and remove them?
4) How to compare two arrays (multidimensional also?
- To search if a value exists in simple array, simply use
in_array
, to get value's key, usearray_search
. For multidimensional arrays write a recursive function, that will search for values, and recurse if a value is an array (sub array). - Let the above function return total found, and sum all sub recursions return values.
- To catch duplicates in:
- Multidimensional arrays: a recursive function with the same concept of the above
- Simple arrays: keys won't duplicate for sure, and use
array_unique
to remove duplicates (you can check the array length before and after to see if anything got removed, which means a duplicate was found). - the search results should be a simple array, pass it to the above one.
- to remove them;
array_unique
as stated above.
- to compare arrays:
array_ intersect
andarray_ diff
, for multidimensional use those functions user-callback variation to achieve what you want.
Also have a look at PHP Array Functions.
To remove duplicates try this: array_unique
Count number of search results:
$values = array_count_values($array);
$count = $values[$value]; //$value is what you search for
Search: array_search
Duplicates: in_array
Compare: array_diff OR array_intersect
As for their multidimensional counterparts - just scroll through the user comments on the bottom on each functions page, you'll be sure to find a nice function thats been contributed by someone.
To the number of keys in an array, you can simply use the count()
function, as it accepts arrays. So, to count your search results, you can do the following:
count(array_search("1", $array)); //1 being the needle and $array the haystack
精彩评论