user2029890
user2029890

Reputation: 2713

How to get a value from an array

Not sure why I can't this to work. My json is:

[values] => Array
        (
            [0] => Array
                (
                    [field] => id1
                    [value] => 985
                )

            [1] => Array
                (
                    [field] => id2
                    [value] => 6395
                )

            [2] => Array
                (
                    [field] => memo
                    [value] => abcde
                )

I simply want the values of id2

I tried:

foreach ($json['values'] as $values) {  
    foreach ($json as $key=>$data) {
        if ($data['field'] == 'id2') {
            $result = $data['value'];
            print '<br>value: '.$result;
        }
    }
}

Thanks. I know this should be relatively simple and I'm sure I've done this correctly before.

Upvotes: 0

Views: 89

Answers (4)

Tadas Sasnauskas
Tadas Sasnauskas

Reputation: 2313

Assuming there might be multiple fields with the same name and you want them all as array, here's an alternative take:

array_filter(array_map(function($item) { return $item['field'] == 'id2' ? $item['value'] : null; }, $json['values']));

If your field names are always unique and you just want a single scalar:

array_reduce($json['values'], function($current, $item) { return $item['field'] == 'id2' ? $item['value'] : $current; });

(note that this one is not ideal since it will walk all the array even if match is found in first element)

And here's a gist with both in this and function form + output.

Upvotes: 0

CodeBird
CodeBird

Reputation: 3858

foreach ($json['values'] as $values) { //you're looping your first array, puttin each row in a variable $values
    foreach ($values as $key=>$data) {  //you're looping inside values taking the array index $key and the value inside that index $data
        if ($key == 'id2') { //test if $key (index) is = to id2
            print '<br>value: '.$value; // print the value inside that index
        }
    }
}

this is just an explanation, to what is going wrong with your code, but as @Pawel_W there is no need for the second foreach loop you can directly test

if($values['field']=='id2'){ print $values['value'];}

Upvotes: 0

Vahan
Vahan

Reputation: 534

I think you just need to use array_search. And here is recursive array_search ;

Upvotes: 0

pwolaq
pwolaq

Reputation: 6381

there's no need for inner loop, after the first one $values already contain the exact array that you are looking for

foreach ($json['values'] as $values) // $values contain 
{
    if ($values['field'] == 'id2')
    {
        $result = $values['value'];
        print '<br>value: '.$result;
    }
}

Upvotes: 1

Related Questions