如果我已经有了数组的子值,我如何获取父键和值?

How can i get the parent key and value if i already have children value of an array?

我无法弄清楚如何借助多维数组的子键值来获取父键和值。

我有一个格式如下的数组:

[91] => Array
    (
        [description] => Charged
        [boundingPoly] => Array
            (
                [vertices] => Array
                    (
                        [0] => Array
                            (
                                [x] => 244
                                [y] => 438
                            )

                        [1] => Array
                            (
                                [x] => 287
                                [y] => 438
                            )

                        [2] => Array
                            (
                                [x] => 287
                                [y] => 452
                            )

                        [3] => Array
                            (
                                [x] => 244
                                [y] => 452
                            )

                    )

            )

    )

我正在获取并存储键值 ['x']:

foreach($array as $box){
     if($box['description']=="Charged"){
            $lbl_row_arr[] = $box['boundingPoly']['vertices'][0]['x'];
     }
}

所以现在我在这个例子中 'x' 的值是“244”。我的问题是,如果我有 'x' 的值,我怎样才能得到 'description' 键的值?

同时输入description值和x值:

foreach($array as $box){
     if($box['description']=="Charged"){
            $tmp = [
                'value_x' => $box['boundingPoly']['vertices'][0]['x'],
                'descr'   => $box['description'], 
            ];
            $lbl_row_arr[] = $tmp;
     }
}

$x = 244;
echo $lbl_row_arr[array_search($x,array_column($lbl_row_arr,'value_x'))]['descr'];

您可以使用 in_arrayarray_column 来搜索每个框的 x 值,如果 x 值,则返回该框的 description找到:

$x = 244;
foreach ($array as $box) {
    if (in_array($x, array_column($box['boundingPoly']['vertices'], 'x'))) {
        $descr = $box['description'];
        break;
    }
}
if (isset($descr)) {
    echo "found $descr with x = $x\n";
}

输出(用于您的示例条目):

found Charged with x = 244

Demo on 3v4l.org