PHP如果数组是多维的,如何从值中获取关键字名称


PHP How to get key name from value if array is multidimensional

我有下面的数组并得到这个结果:

Array
(
    [0] => stdClass Object
        (
            [UnitIdx] => 10
            [Title] => 순차
            [Description] => 
            [NumSteps] => 9
            [ThumbnailPathName] => Level_1_Unit_thumbnail_Small.png
            [Step_1] => 4
            [Step_2] => 5
            [Step_3] => 6
            [Step_4] => 7
            [Step_5] => 8
            [Step_6] => 9
            [Step_7] => 10
            [Step_8] => 11
            [Step_9] => 12
            [Step_10] => 0
            [Step_11] => 0
            [Step_12] => 0
            [Step_13] => 0
            [Step_14] => 0
            [Step_15] => 0
            [Step_16] => 0
            [Step_17] => 0
            [Step_18] => 0
            [Step_19] => 0
            [Step_20] => 0
        )
)

现在我想找到键形式值。例如,值为11,所以关键字为Step_8

知道如何从值中返回密钥名称吗?

谢谢。

您可以使用array_search()按值搜索键,并通过类型转换将Object转换为PHP数组,下面是一个示例:

<?php
    $object = array();
    $object[0] = new StdClass;
    $object[0]->foo = 1;
    $object[0]->bar = 2;
    echo "<pre>";
    print_r($object);
    echo "</pre>";
    $key = array_search ('2', (array) $object[0]);
    echo "<pre>";
    print_r($key);
?>

输出:

Array
(
    [0] => stdClass Object
        (
            [foo] => 1
            [bar] => 2
        )
)
bar

看看这个:

<?php
//this part of code is for prepare sample data which is similar to your data
$class = new stdClass;
$class->prop1 = 'prop1';
$class->prop2 = 'prop2';
$array = array($class);
//THIS IS METHOD FOR SEARCH KEY BY VALUE
print_r(array_search('prop1',json_decode(json_encode($array[0]), true))); //you are looking for key for value 'prop1'

检查工作小提琴:点击

解释:

1)json_decode(json_encode($array[0]), true)-因为数组中有stdClass对象,所以不能使用array_search函数。因此,此行将$array[0]元素(即stdClass对象)转换为数组。现在我们可以使用array_search函数按特定值搜索关键字。

2)print_r(array_search('prop1',json_decode(json_encode($array[0]), true)));-我们使用array_search函数来获取数组元素的键,该键的值等于prop1。该功能的文档显示:

array_search—在数组中搜索给定值并返回如果成功,则对应密钥

因此,我们得到了对应于prop1值的密钥,即prop1。CCD_ 14函数给出了结果。相反,您可以将运算结果分配给变量,并将其用于代码的其他部分,例如:

$variable = array_search('prop1',json_decode(json_encode($array[0]), true));