如何从数组中获取值

时间:2014-02-14 22:27:32

标签: php foreach

不知道为什么我不能这样做。我的json是:

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

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

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

我只想要id2的值

我试过了:

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

感谢。我知道这应该相对简单,我确信我之前已经做到了这一点。

4 个答案:

答案 0 :(得分:1)

在第一个$values已经包含您正在寻找的确切数组之后,不需要内循环

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

答案 1 :(得分:0)

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
        }
    }
}

这只是一个解释,你的代码出了什么问题,但是@Pawel_W不需要第二个foreach循环你可以直接测试

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

答案 2 :(得分:0)

我认为你只需要使用array_search。 这是recursive array_search;

答案 3 :(得分:0)

假设可能有多个具有相同名称的字段,并且您希望它们都作为数组,这里是另一种选择:

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

如果您的字段名称始终是唯一的,并且您只需要一个标量:

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

(请注意,这个并不理想,因为即使在第一个元素中找到匹配,它也会遍历所有数组)

here's a gist同时使用此函数和函数形式+输出。

相关问题