0

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.

2
  • Can you show any code attempts? My first suggestion would be to think about how to derive a data structure against which you can perform the lookup you want. Beyond that, you should at least be able to cobble together a brute force approach and show you efforts here. Commented Aug 18, 2014 at 13:51
  • 1
    possible duplicate of PHP - Accessing Multidimensional Array Values Commented Aug 18, 2014 at 13:51

3 Answers 3

1

A simple alternative using array_keys:

function getValues($data, $lookForValue, $column)
{
    $res = array();

    foreach ($data as $key => $data) 
    {
        if($idx = array_keys($data, $lookForValue))
        {
            $res[$idx[0]] = $data[$column];
        }
    } 

    return $res;
}

$values = getValues($myData, "quantity", "dbfield");

var_dump($values);
Sign up to request clarification or add additional context in comments.

Comments

1

echo out the array as such..

$array = array();

$array['qty'] = 'qtty';
$array['dbfield'] = 'QUANTITY_NEW';

if($array['qty'] = 'qtty'){

echo $array['dbfield'];

} 

returns - QUANTITY_NEW

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.