如何获取对象在数组中的位置?

问题描述 投票:0回答:1

我的阵列:

$array = array(
    'test' => new Object(2),
    'two' => new Object(22),
    'other' => new Object(12),
    'five' => new Object(23),
    'next' => new Object(42),
);

我怎样才能在这个数组中获得位置?

我有变量:

$object = Object(12);

所以我想收到:

$position = 3; //or 2 if we number from 0

array_keys在此示例中不起作用...

php
1个回答
0
投票

你可以使用$position = array_search($object, array_values($array), true) + 1;

array_search manualarray_values manual

使用array_values,您可以删除密钥并获取索引数组。因为您需要位置而不是元素的索引需要向其添加1。

Working example

© www.soinside.com 2019 - 2024. All rights reserved.