【问题标题】:php select X items from set?php从集合中选择X项?
【发布时间】:2011-05-28 14:43:39
【问题描述】:

我正在使用代码点火器从数据库中检索数据

返回的是一个数组对象

类似

array(
  [0] = {
    mobile => '027xxxxxx',
    id     => 1
  },
  [1] = {
    mobile => '027xxxxxx',
    id     => 4
  },
  [2] = {
    mobile => '027xxxxxx',
    id     => 5
  },
  [3] = {
    mobile => '027xxxxxx',
    id     => 7
  },
  [4] = {
    mobile => '027xxxxxx',
    id     => 9
  },
  [5] = {
    mobile => '027xxxxxx',
    id     => 10
  },
  [6] = {
    mobile => '027xxxxxx',
    id     => 112
  },
  [7] = {
    mobile => '027xxxxxx',
    id     => 113
  }
)

我有一个名为 count 的变量,它包含一个任意数字(尽管总是小于数组中对象的数量)。

我的问题是:

count = 3, 如何从对象中获取 3 个随机 id 的数组?

类似array(4, 9, 1)

我只想得到一个 id 一次

所以array(4, 4, 9) 是不正确的。

请注意,id 不是线性的。

【问题讨论】:

    标签: php arrays random object


    【解决方案1】:
    $random_keys = array_rand(array_keys($your_array), 3);
    

    array_rand

    解释-

    • array_keys 只返回原始数组中的键
    • array_rand 然后会随机选择,没有重复性
    • 返回的数组包含原始数组的键
    • 这样您就可以从原始数组中检索任何信息

    【讨论】:

    • 你不会相信我要把它弄得多么复杂;)
    • @alreal:太棒了! @Zenph 也一样!
    猜你喜欢
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多