我想获取没有foreach的数组的索引。这是示例数组
$this->rci_db->select ("
$this->tbl_register.id,
$this->tbl_register.cor,
DATE_FORMAT($this->tbl_register.registerdate, '%d/%m/%Y') AS registerdate,
$this->tbl_registrations.registration,
$this->tbl_aircrafts.cn,
$this->tbl_aircrafts.built,
$this->tbl_manufacturers.manufacturer,
$this->tbl_models.type AS model,
COUNT($this->tbl_images.imgid) AS count
");
$this->rci_db->from("$this->tbl_register");
$this->rci_db->join("$this->tbl_registrations", "$this->tbl_registrations.rid = $this->tbl_register.rid", 'left');
$this->rci_db->join("$this->tbl_aircrafts", "$this->tbl_register.aid = $this->tbl_aircrafts.aid", 'left');
$this->rci_db->join("$this->tbl_manufacturers", "$this->tbl_manufacturers.mid = $this->tbl_aircrafts.mid", 'left');
$this->rci_db->join("$this->tbl_models", "$this->tbl_models.tid = $this->tbl_aircrafts.tid", 'left');
$this->rci_db->join("$this->tbl_images", "$this->tbl_register.id = $this->tbl_images.id", 'left');
$this->rci_db->where("$this->tbl_register.rid", $rid);
$query = $this->rci_db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
return false;
假设我的数据是 gcr_id = 21 ,通过与上述数组进行比较,它应该为我提供数组的索引 3 >
答案 0 :(得分:4)
您可以结合使用array_search
和array_column
。 array_column
返回具有键'gcr_id'
的所有值,然后array_search
返回对应于值21
的键。
$array = array(
array('gcr_distance' => 31.0, 'gcr_id' => 23),
array('gcr_distance' => 28.0, 'gcr_id' => 22),
array('gcr_distance' => 26.0, 'gcr_id' => 20),
array('gcr_distance' => 110.0, 'gcr_id' => 21)
);
$key = array_search(21, array_column($array, 'gcr_id'));
echo $key;
输出:
3
受@Elementary评论的启发,我对此进行了一些基准测试。我发现,在100k条目数组中,当条目不在数组中时,array_search
和array_column
花费的时间是基于foreach
的搜索的95%其中正在调用array_column
。因此,似乎平均而言,基于foreach
的搜索会更快。