简体   繁体   中英

PHP array_unique without index

I've been trying to find something similar to array_unique() to the extent or removing all the duplicates from an array. However in this particular case I need a comma spaced array as the result rather than an key value pair. What I'd like to do is avoid running this through a loop to do it, if I can.

So if theres something like array_unique() or something I can apply to my array there after to strip the numeric index out then I am all ears for suggestions.

Currently I am building the initial array through a loop, this look cycles over 5 to 150,000 entries of which one particular entry can have any of about 1,000 possible 3 dot style versioning numbers. This is what I am building this array of. So I have many duplicates put into the array

example:

$myarray = array();
foreach($obj as $prod)
{
   //cycling over the master loop adding all my other stuff and building it out..
   $myarray[] = $prod['version'];
}

which gives me quite a large array in the format I'd like just

Array(
   "1.0.0",
   "1.0.1",
   "3.0.2220",
   "2.0.0",
   "2.0.1",
   "1.8.11",
   "3.0.2220",
   "3.0.2220",
   "2.0.0",
   "2.0.0",
   "2.0.0"
)

Where afte the loop is complete I do.

$myarray = array_unique($myarray);

Which leaves me with an array like

Array(
  [0] = "1.0.0",
  [1] = "1.0.1",
  [2] = "3.0.2220",
  [3] = "2.0.0",
  [4] = "2.0.1",
  [5] = "1.8.11",
)

Which is not desired, what is desired as the end result is..

Array(
   "1.0.0",
   "1.0.1",
   "3.0.2220",
   "2.0.0",
   "2.0.1",
   "1.8.11",
)

Where I can then sort it out to list in order earliest to latest versions..

This:

Array(
  [0] = "1.0.0",
  [1] = "1.0.1",
  [2] = "3.0.2220",
  [3] = "2.0.0",
  [4] = "2.0.1",
  [5] = "1.8.11",
)

and this:

Array(
   "1.0.0",
   "1.0.1",
   "3.0.2220",
   "2.0.0",
   "2.0.1",
   "1.8.11",
)

are the same thing, in PHP all arrays have an index, in the last example it's just that is not printing them, but they are there, and if you have not explicitly specified the indexes, they are just sequencial integer numbers starting from zero, like the first example.

In your last example, the one which apparently has no indexes, if we call it $array we can do the following to print its indexes:

foreach ($array as $key => $value) {
   echo $key; //this will print the indexes of the array
}

You are wanting an array without keys? Every array has keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM