douhong6187 2012-10-01 18:23
浏览 46
已采纳

没有索引的PHP array_unique

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..

  • 写回答

2条回答 默认 最新

  • doujiepin5547 2012-10-01 18:28
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀