PHP: How can I get the value of a key in a multiple array

advertisements

The multiple array looks like

Array
(
    [id] => description
    [header] =>
    [width] => 20
    [dbfield] => description
    [type] => text
)
Array
(
    [id] => quantity
    [header] => Menge
    [dbfield] => QUANTITY_NEW
    [width] => 60
    [type] => decimal
)

How can I get the value from dbfield where id is 'quantity' without knowing the numeric value of the id?

The actual code looks like

foreach($array as $id => $fieldData) {

   if($fieldData['type'] == 'decimal')
   {
     doSomething...();
   }
}

In the part with doSomething I need access to other fields from the array, but I only know the id. I already tried it with dbfield['quantity']['dbfield'] etc. which obviously fails.


You can do this with several methods, one of them is using array_map to get those values:

$dbfield = array_filter(array_map(function($a){
    if($a["id"] === "quantity"){
        return $a["dbfield"];
    }
}, $array));

print_r($dbfield);

You iterate over the array, and return the key dbfield where id is 'quantity'. Array filter is just to not return null values where it doesn't have 'quantity' id.

Online attempt to reproduce your code can be found here