0

I am unable to figure out how to get the parent key and value with the help of it's child's key value of multidimensional array.

I have an array in the format like this:

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

                    )

            )

    )

I am getting and storing the value of the key ['x']:

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

So now i have value of 'x' in this example is "244". My question is how can i get the value of 'description' key if i have the value of 'x'?

Neeraj Kumar
  • 506
  • 1
  • 8
  • 19

2 Answers2

1

Put description value with x value at the same time:

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'];
Aksen P
  • 4,564
  • 3
  • 14
  • 27
1

You can use in_array with array_column to search the x values for each box, returning the description for that box if the x value is found:

$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";
}

Output (for your sample entry):

found Charged with x = 244

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95