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