简体   繁体   English

PHP:如何从多个数组中的键获取值

[英]PHP: How can I get the value from a key in a multiple array

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? 在不知道id的数值的情况下,如何从dbfield获得id为'quantity'的值?

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. 在doSomething部分中,我需要访问数组中的其他字段,但是我只知道ID。 I already tried it with dbfield['quantity']['dbfield'] etc. which obviously fails. 我已经用dbfield ['quantity'] ['dbfield']等尝试了,但是显然失败了。

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

A simple alternative using array_keys : 使用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);

You can do this with several methods, one of them is using array_map to get those values: 您可以使用几种方法来执行此操作,其中一种方法是使用array_map获取这些值:

$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'. 您遍历数组,并返回id为'quantity'的键dbfield Array filter is just to not return null values where it doesn't have 'quantity' id. 数组过滤器只是为了不返回没有“数量” ID的空值。

Online attempt to reproduce your code can be found here 可在此处找到在线重现代码的尝试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM