-2

I have following array and getting this result:

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

Now I want to find key form value. For example value is 11 so key is Step_8.

Any idea how to return key name from value?

Thanks.

Mr.Happy
  • 2,639
  • 9
  • 40
  • 73

2 Answers2

0

Take a look at this:

<?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'

Check working fiddle: CLICK!

Explanation:

1) json_decode(json_encode($array[0]), true) - because you have in your array stdClass object, you can't use array_search function. So this line converts $array[0] element, which is stdClass object to an array. Now we can use array_search function to search key by specific value.

2) print_r(array_search('prop1',json_decode(json_encode($array[0]), true))); - we are using array_search function to get key of array element which value is equal to prop1. Documentation of this function says:

array_search — Searches the array for a given value and returns the corresponding key if successful

So we getting key corresponding to prop1 value, which is prop1. print_r function shows us result. Instead of that you can assign result of operation to a variable and use it in other parts of code, for example:

$variable = array_search('prop1',json_decode(json_encode($array[0]), true));
aslawin
  • 1,981
  • 16
  • 22
0

You can search your key by value using array_search() and converting your Object into PHP array by typecasting, below is an example:

<?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);

?>

Output:

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

)

bar
hmd
  • 960
  • 2
  • 9
  • 13