开发者

Search inside arrays, count, find duplicates, compare [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.

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 question

Several 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?


  1. To search if a value exists in simple array, simply use in_array, to get value's key, use array_search. For multidimensional arrays write a recursive function, that will search for values, and recurse if a value is an array (sub array).
  2. Let the above function return total found, and sum all sub recursions return values.
  3. To catch duplicates in:
    1. Multidimensional arrays: a recursive function with the same concept of the above
    2. 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).
    3. the search results should be a simple array, pass it to the above one.
    4. to remove them; array_unique as stated above.
  4. to compare arrays: array_ intersect and array_ 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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜