-1

I have an array like this:

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
    )

How can I get individual values from key for example, I would like to output the setValue of isMetric.

Thanks

1

3 Answers 3

1
foreach ($foo as $bar) {
    if ($bar['name'] == "isMetric") {
        // Use setValue here
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Please use this solution with care. If you need to access the property often it makes sense to convert the array first so you can access the key anytime without loosing performance.
@androidavid What you said is valid but I just went with a simple loop because if someone needs to access a specific element outside of when looping against the whole collection often then it should probably just be a class in the first place instead of making an array to act as an object
1

From what I understand you want to do something like $myArray['isMetric']['setValue'].

As your array is not in that form you need to map it that way.

$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'];

Run this code here: https://repl.it/CZ3R

Comments

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

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.