如何在PHP中循环遍历这些值

时间:2015-11-08 17:16:22

标签: php

如何在PHP中循环遍历json_decode($ json_emp)输出并获取值?

    $array_emp = json_decode($json_emp);
    var_dump( $array_emp)

        {"info":[{"id":"10","name":"employee1"},{"id":"11","name":"employee2"},{"id":"12","name":"emplyee3"}]}

需要查找获取ID和名称的各个值。这是阵列。

$array_emp = json_decode($json_emp,true);

Array
(
    [info] => Array
        (
            [0] => Array
                (
                    [id] => 10
                    [name] => employee1
                )

            [1] => Array
                (
                    [id] => 11
                    [name] => employee2
                )

            [2] => Array
                (
                    [id] => 12
                    [name] => emplyee3
                )

        )

)

这是对象;

stdClass Object
(
    [info] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 10
                    [name] => employee1
                )

            [1] => stdClass Object
                (
                    [id] => 11
                    [name] => employee2
                )

            [2] => stdClass Object
                (
                    [id] => 12
                    [name] => emplyee3
                )

        )

)

请让我知道如何循环使用这些并获取值。尝试了很多,感到困惑。

2 个答案:

答案 0 :(得分:1)

如果您想使用对象,请尝试以下方法:

int -> 'a

对于数组:

foreach ($array_tmp->info as $emp)
{
    echo $emp->name;
}

答案 1 :(得分:1)

使用此

$json = '{"info":[{"id":"10","name":"employee1"},{"id":"11","name":"employee2"},{"id":"12","name":"emplyee3"}]}';

$json = json_decode($json, TRUE);
foreach($json['info'] as $info){
    echo 'ID: '.$info['id'].PHP_EOL;    
    echo 'Name: '.$info['name'].PHP_EOL;    
}

以上代码输出

ID: 10
Name: employee1
ID: 11
Name: employee2
ID: 12
Name: emplyee3

<强> DEMO

如果您处理object而不是array

$json = json_decode($json);
foreach($json->info as $info){
    echo 'ID: '.$info->id.PHP_EOL;  
    echo 'Name: '.$info->name.PHP_EOL;  
}

将输出与上面相同的内容。

<强> DEMO