使用key从数组中获取值

时间:2016-06-08 02:51:10

标签: php

我有一个这样的数组:

Array
(
[0] => Array
    (
        [settingID] => 1
        [name] => audioCueDistance
        [setValue] => false
    )

[1] => Array
    (
        [settingID] => 2
        [name] => audioCueDistanceToGo
        [setValue] => true
    )

[2] => Array
    (
        [settingID] => 3
        [name] => audioCues
        [setValue] => true
    )

[3] => Array
    (
        [settingID] => 4
        [name] => audioCueStyle
        [setValue] => default
    )

[4] => Array
    (
        [settingID] => 5
        [name] => audioCueTime
        [setValue] => true
    )

[5] => Array
    (
        [settingID] => 6
        [name] => isMetric
        [setValue] => true
    )

如何从key中获取单个值,例如,我想输出isMetric的setValue。

由于

3 个答案:

答案 0 :(得分:1)

foreach ($foo as $bar) {
    if ($bar['name'] == "isMetric") {
        // Use setValue here
    }
}

答案 1 :(得分:1)

根据我的理解,你想做$myArray['isMetric']['setValue']

之类的事情

由于您的数组不是那种形式,您需要以这种方式进行映射。

$myArray = array(
    array(
        'settingID'=>6,
        'name'=>'isMetric',
        'value'=>true
    )   
);

$myAssocArray = array_reduce($myArray, function($carry, $item){
    $carry[$item['name']] = $item;
    return $carry;
}, array());

echo $myAssocArray['isMetric']['setValue'];

在此处运行此代码:https://repl.it/CZ3R

答案 2 :(得分:0)

foreach($array as $element)
{
    if($element['name'] = 'isMetric')
        return $element['setValue'];
}
throw new \Exception('isMetric Not Found.');